解决Python Requests爬虫返回403错误,即使加了特征请求头和代理也无法解决的问题处理方法

一、问题分析

【疑惑】:使用python的requests库发起get或post请求返回403代码错误,使用postman发起请求发现状态码<200>竟然成功了。这是什么原因?首先排除ip问题,ip有问题的话postman也访问不了。难道是headers出现了问题吗,通过对比发现也不是headers的问题。那就奇了怪了?

【解疑】:其实遇到这种情况大概率是遇到了“原生模拟浏览器 TLS/JA3 指纹的验证”,浏览器和postman都有自带指纹验证,而唯独requests库没有。这就让反爬有了区分人为和爬虫的突破口。

二、问题解决

1、使用 pyhttpx 库(推荐)

1.1、安装

pip install pyhttpx

1.2、代码示例

import pyhttpx

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
}
session = pyhttpx.HttpSession()
res = session.get(url='https://www.baidu.com/',headers=headers)
print(res.text)

2、使用 curl_cffi 库(用得少)

2.1、安装

pip install curl_cffi

2.2、代码示例

from curl_cffi import requests
res = requests.get(url='https://www.baidu.com/',impersonate="chrome101")
print(res.text)

3、使用httpx库(极力推荐)

3.1、安装

pip install httpx

3.2、代码示例

import httpx

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
}

res = httpx.get(url='https://www.baidu.com/', headers=headers, timeout=10, verify=False)
print(res.text)
物联沃分享整理
物联沃-IOTWORD物联网 » 解决Python Requests爬虫返回403错误,即使加了特征请求头和代理也无法解决的问题处理方法

发表评论