爬虫的时候出现问题,得不到数据,搜索了一下,说可能被反爬,但是写了headers也没有用,标签也看了没有输错,求解,不知道是不是哪里代码敲错了还是被反爬了,还是没有安装什么模块。求解决
'''
你找错位置了,数据真正的接口不是 https://ys.endata.cn/BoxOffice/Ranking
而是 https://ys.endata.cn/enlib-api/api/home/getrank_mainland.do ,
分析接口请求后,编写爬虫代码如下
'''
import requests
import random
start_url = 'https://ys.endata.cn/enlib-api/api/home/getrank_mainland.do'
headers = {
'User-Agent':"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
'Host':'ys.endata.cn',
'Refer':'https://ys.endata.cn/BoxOffice/Ranking'
}
form_data = {
'r': str(random.random()), # 0.9684041165722543 0.2844434404480951 0.056809053050767444 0.40809026266514836
'top': 50,
'type': 0
}
result = requests.post(start_url,headers=headers,data=form_data).json()
print(result.get('data').get('table0'))
你写了header,但是你没有用到啊。requests.get('xxxxxxxx', headers=headers)
这个是动态网页,二次加载的。你这种方式是请求不到数据的,除非用selenium。这个网站有api接口。
import requests
cookies = {
'route': '4e39643a15b7003e568cadd862137cf3',
'Hm_lvt_82932fc4fc199c08b9a83c4c9d02af11': '1683677710',
'Hm_lpvt_82932fc4fc199c08b9a83c4c9d02af11': '1683678370',
}
headers = {
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7',
'Connection': 'keep-alive',
'Content-Type': 'application/x-www-form-urlencoded',
# 'Cookie': 'route=4e39643a15b7003e568cadd862137cf3; Hm_lvt_82932fc4fc199c08b9a83c4c9d02af11=1683677710; Hm_lpvt_82932fc4fc199c08b9a83c4c9d02af11=1683678370',
'Origin': 'https://ys.endata.cn',
'Referer': 'https://ys.endata.cn/boxoffice/ranking',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-origin',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36',
'sec-ch-ua': '"Google Chrome";v="113", "Chromium";v="113", "Not-A.Brand";v="24"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
}
data = {
'r': '0.25639328006270223',
'top': '50',
'type': '0',
}
response = requests.post(
'https://ys.endata.cn/enlib-api/api/home/getrank_mainland.do',
cookies=cookies,
headers=headers,
data=data,
)
headers中有很多字段,这些字段都有可能会被对方服务器拿过来进行判断是否为爬虫
1.1 通过headers中的User-Agent字段来反爬
1.2 通过referer字段或者是其他字段来反爬
1.3 通过cookie来反爬