爬虫如何爬取猫眼电影TOP榜数据
今天爬蟲代理就為大家分享一下,爬蟲是如何爬取貓眼電影TOP榜數(shù)據(jù)的。主要抓取的內容有排名、圖片、電影名稱、主演、上映時間和評分信息。在抓取之前,我們先打開貓眼電影TOP100頁面,研究分析頁面,查找我們需要的信息位置,然后抓取。
代碼如下:
import json
import requests
from requests.exceptions import RequestException
import re
import time
def get_one_page(url):
try:
headers = { 'User-Agent': 'agent信息'}response = requests.get(url, headers=headers)if response.status_code == 200:return response.textreturn Noneexcept RequestException:
return Nonedef parse_one_page(html):
pattern = re.compile(’
items = re.findall(pattern, html)
for item in items:
yield {'index': item[0],'image': item[1],'title': item[2],'actor': item[3].strip()[3:],'time': item[4].strip()[5:],'score': item[5] + item[6]}def write_to_file(content):
with open(‘result.txt’, ‘a’, encoding=‘utf-8’) as f:
f.write(json.dumps(content, ensure_ascii=False) + '\n')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)time.sleep(1) 通過上述代碼,我們就可以獲取到貓眼電影TOP榜數(shù)據(jù)信息了
總結
以上是生活随笔為你收集整理的爬虫如何爬取猫眼电影TOP榜数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: elasticsearch6.5.4破解
- 下一篇: 【Python办公自动化】使用repor