栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

爬虫 403 requests 增加 header 代理ip

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

爬虫 403 requests 增加 header 代理ip

当爬虫遇到了403,有可能的原因主要有:

1. 你的User-Agent暴露了你,解决方案,增加header
import requests
import cfscrape
from urllib import request
from urllib import parse
from http.cookiejar import cookieJar

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

target_url = "www.baidu.com"
resp = requests.get(target_url, headers=headers)
print(resp)
print(resp.status_code)
print(resp.text)
关于如何获取user-agent:

1. 自动获取:使用现成的库,https://github.com/hellysmile/fake-useragent

2.手动获取:打开你需要爬虫的网页,右键 检查, 刷新网页,network下随便点一个,在request headers中获取

2.你的爬虫太频繁了,ip被封了,使用代理ip
import requests
import cfscrape
from urllib import request
from urllib import parse
from http.cookiejar import cookieJar


target_url = "www.baidu.com"
proxymeta = "http://host:port"
proxies = {

    "http": proxymeta,
    "https": proxymeta
}
resp = requests.get(target_url, proxies=proxies)
print(resp)
print(resp.status_code)
print(resp.text)

代理ip你可以买,当然也可以用一些免费的,参考:

GitHub - constverum/ProxyBroker: Proxy [Finder | Checker | Server]. HTTP(S) & SOCKS

3. 跳过cloudflare 验证

如果你把resp.text 的内容,用浏览器打开之后,显示了这个Please stand by, while we are checking your browser.就需要用这中方法解决

#pip install cloudscraper
import cloudscraper
scraper = cloudscraper.create_scraper()
ret = scraper.get(target_url)
print(ret)
print(ret.status_code)

reference : GitHub - VeNoMouS/cloudscraper: A Python module to bypass Cloudflare's anti-bot page.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/303283.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号