Python使用requests设置headers、cookies实现猫眼实时电影票房排行榜爬取
程序员文章站
2022-04-25 17:00:17
...
解析爬取方法
打开解析猫眼
首先,打开网址猫眼官网,然后选择开发者模式进行编辑。
我们可以看到有一个ajax的数据在实时渲染,我们双击点开这个ajax文件,看一看里面到底是什么?
爬取步骤GIF
代码部分
实现代码
#猫眼数据爬取.py
import requests
headers = {'Accept': '*/*',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'max-age=0',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
'Connection': 'keep-alive',
'Referer': 'https://piaofang.maoyan.com/dashboard'
}
cookies = r'_lxsdk_cuid=172d168b465c8-07694b0d6af31b-f7d123e-144000-172d168b466c8; _lxsdk=32FE24C0B2E611EA8A833903D31672838A2F645D21064B67B77010041BC9A3BF; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1592651238; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1592651238; __mta=150257545.1592651244500.1592651244500.1592651244500.1; _lx_utm=utm_source%3DBaidu%26utm_medium%3Dorganic; _lxsdk_s=172d168b46f-ae0-993-411%7C%7C12; __mta=150257545.1592651244500.1592651244500.1592651283319.2'
cookies_dict={}#初始化cookies字典变量
for line in cookies.split(';'): #按照字符:进行划分读取
#其设置为1就会把字符串拆分成2份
name,value=line.strip().split('=',1)
cookies_dict[name]=value
web = requests.get("http://piaofang.maoyan.com/dashboard-ajax?orderType=0&uuid=172d168b465c8-07694b0d6af31b-f7d123e-144000-172d168b466c8&riskLevel=71&optimusCode=10",cookies = cookies_dict,headers = headers)
web = web.text
print(web)
with open(r"./maoyan.txt","w+")as f:
f.write(web)
f.close()
教程
暂时没有