由于猫眼TOP100榜网页是静态网页,用requests库就可以获取到完整的网页源代码,然后用BeautifulSoup4库进行解析。
首先分析网页的url:
通过分析便可以得到网址为:
# i的值为0,10,20,... 对应的分别是第1页,第2页,第3页,...
url = "http://maoyan.com/board/4?offset=" + str(i)
使用一个迭代便可以构造全部网页的url:
for i in range(10):
i = i * 10
url = "http://maoyan.com/board/4?offset=" + str(i)
然后用requests库去获取网页源代码,再用BeautifulSoup4库进行解析,定义解析函数html_page_parser(html):
def html_page_parser(html):
soup = BeautifulSoup(html, 'html5lib')
for dd_tag in soup.find_all('dd'):
items = [] # 创建一个列表来存储数据
for p_tag in dd_tag.find_all('p'):
items.append(p_tag.string)
# 开始写入到本地文件
with open("/home/zhiying/文档/maoyan_top100_films_results1.txt", 'a', encoding='utf-8') as f:
f.write(dd_tag.i.string + ' ' + items[0].strip() + ' ' + items[1].strip() + ' ' + items[2].strip() + \
' ' + 'http://maoyan.com' + dd_tag.p.a['href'] + '\n')
写入模式用'a' 不用'wt',是因为用'wt'时当写入下一页时会覆盖前一页的内容。
至此,获取猫眼TOP100榜的爬虫就完成了。