爬豆瓣网,root_html一直获取不到数据,怎么解决
来源:13-7 正则分析HTML

cherrylove123
2018-07-15
#!/usr/bin/python
# -*- coding: utf-8 -*-
from urllib import request
import re
# 获取豆瓣网音乐人的专辑名称和喜欢的人数
class Spider():
url = 'https://music.douban.com/artists/genre_page/6/'
root_pattern = '<div style="width:100%;" class="11">([\s\S]*?)</div>'
name_pattern = '<a>([\s\S]*?)</a>'
number_pattern = '<div class="p1">([\s\S]*?)</div>'
#获取源文档
def __content(self):
r = request.urlopen(Spider.url)
htmls = r.read()
htmls = str(htmls, encoding='utf-8')
return htmls
#对源文档进行提炼,提取专辑名和喜欢的人数
def __analisys(self,htmls):
root_html = re.findall(Spider.root_pattern, htmls)
anchors = []
for html in root_html:
name = re.findall(Spider.name_pattern, html)
number = re.findall(Spider.number_pattern, html)
anchor = {'name': name, 'number': number}
anchors.append(anchor)
print(anchors)
def go(self):
htmls = self.__content()
self.__analisys(htmls)
#调用
spider = Spider()
spider.go()
2回答
-
主要是正则表达式出的问题
root_pattern = '<div style="width: 100%;" class="ll">([\s\S]*?)</div>'
name_pattern = '<a [\s\S]*?>([\s\S]*?)</a>'
number_pattern = '<div class="pl">([\s\S]*)'
width:与100%之间有个空格
class="ll"、class="pl" (是字母L小写不是数字1)
a标签中还有href属性所以'<a>([\s\S]*?)</a>'是无法匹配的
通过'<div style="width: 100%;" class="ll">([\s\S]*?)</div>' 获取的字符串最后是没有</div>的所以直接用'<div class="pl">([\s\S]*)'匹配
012018-09-26 -
丶灰色天空
2018-09-10
#!/usr/bin/python
# -*- coding: utf-8 -*-
from urllib import request
import re
# 获取豆瓣网音乐人的专辑名称和喜欢的人数
class Spider():
url = 'https://music.douban.com/artists/genre_page/6/'
root_pattern = '<div style="width: 100%;" class="ll">([\s\S]*?)</div>'
name_pattern = '<a [\s\S]*?>([\s\S]*?)</a>'
number_pattern = '<div class="pl">([\s\S]*)'
#获取源文档
def __content(self):
r = request.urlopen(Spider.url)
htmls = r.read()
htmls = str(htmls, encoding='utf-8')
return htmls
#对源文档进行提炼,提取专辑名和喜欢的人数
def __analisys(self,htmls):
root_html = re.findall(Spider.root_pattern, htmls)
anchors = []
for html in root_html:
name = re.findall(Spider.name_pattern, html)
number = re.findall(Spider.number_pattern, html)
anchor = {'name': name[0], 'number': number[0]}
anchors.append(anchor)
print(anchors)
def go(self):
htmls = self.__content()
self.__analisys(htmls)
#调用
spider = Spider()
spider.go()
该成这样就行了
00
相似问题