一、环境依赖
python3
依赖库如下:1
pip install request pyquery beautifulsoup4
二、实现
1. 目的
此次爬取猫眼电影排行榜,提取排名、电影名、主演、上映时间、评分、封面图片等。
https://maoyan.com/board/4?offset=0
2. 代码
2.1 爬取函数
1 | def get_one_page(url): |
2.2 re解析函数
1 | def parse_one_page(html): |
2.3 BeautifulSoup解析
1 | def parse_one_page(html): |
2.4 Xpath解析函数
1 | def parse_one_page(): |
2.5 Pyquery解析函数
1 | def parse_one_page(html): |
2.6 写入TXT文件
与*.py一个目录下,新建四个TXT文件。如result_bs4.txt result_pyquery.txt result_re.txt result_xpath.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16def write_to_file(content):
with open('result_pyquery.txt', 'a', encoding='utf-8') as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')
f.close()
def main(offset):
url = 'http://maoyan.com/board/4?offset=' + str(offset)
html = get_one_page(url)
for item in parse_one_page(html):
#print(item)
write_to_file(item)
if __name__ == '__main__':
for i in range(10):
main(offset=i*10)
3. 完整版源码下载
下载源码
欢迎star,谢谢。
三、部分结果一览
1 | {"index": "1", "image": "https://p1.meituan.net/movie/20803f59291c47e1e116c11963ce019e68711.jpg@160w_220h_1e_1c", "title": "霸王别姬", "actor": "张国荣,张丰毅,巩俐", "score": "9.6", "time": "1993-01-01"} |