Python爬虫出现问题得不到数据

爬虫的时候出现问题,得不到数据,搜索了一下,说可能被反爬,但是写了headers也没有用,标签也看了没有输错,求解,不知道是不是哪里代码敲错了还是被反爬了,还是没有安装什么模块。求解决

img

img

'''
你找错位置了,数据真正的接口不是 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,
)

img

  • 建议你看下这篇博客👉 :【Python网络爬虫整理记录 D:04】——关于爬虫伪装中常见headers参数详解以及常见错误代码及错误原因
  • 除此之外, 这篇博客: Python爬虫之常见的反爬手段和解决方法中的 1 通过headers字段来反爬 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
  • headers中有很多字段,这些字段都有可能会被对方服务器拿过来进行判断是否为爬虫

    1.1 通过headers中的User-Agent字段来反爬

    • 反爬原理:爬虫默认情况下没有User-Agent,而是使用模块默认设置
    • 解决方法:请求之前添加User-Agent即可;更好的方式是使用User-Agent池来解决(收集一堆User-Agent的方式,或者是随机生成User-Agent)

    1.2 通过referer字段或者是其他字段来反爬

    • 反爬原理:爬虫默认情况下不会带上referer字段,服务器端通过判断请求发起的源头,以此判断请求是否合法
    • 解决方法:添加referer字段

    1.3 通过cookie来反爬

    • 反爬原因:通过检查cookies来查看发起请求的用户是否具备相应权限,以此来进行反爬
    • 解决方案:进行模拟登陆,成功获取cookies之后在进行数据爬取