python - 尝试使用 Python 3 抓取页面的错误请求
问题描述
我正在尝试使用 python 3 抓取以下页面,但我一直在获取HTTP Error 400: Bad Request
. 我已经查看了一些以前的答案,建议使用urllib.quote
它,因为它是 python 2,所以它对我不起作用。另外,我尝试了另一篇文章建议的以下代码,但仍然没有用。
url = requote_uri('http://www.txhighereddata.org/Interactive/CIP/CIPGroup.cfm?GroupCode=01')
with urllib.request.urlopen(url) as response:
html = response.read()
解决方案
服务器拒绝来自非人类User-Agent
HTTP 标头的查询。
只需选择浏览器的 User-Agent 字符串并将其设置为查询的标题:
import urllib.request
url = 'http://www.txhighereddata.org/Interactive/CIP/CIPGroup.cfm?GroupCode=01'
headers={
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0"
}
request = urllib.request.Request(url, headers=headers)
with urllib.request.urlopen(request) as response:
html = response.read()
推荐阅读
- laravel - MySql phpmyadmin 表到 Laravel 迁移文件
- python - 在声明 range() 时,您是否应该在逗号/s 之后放置一个空格?
- php - WooCommerce 在订单接收端点获取订单 ID 和订单密钥
- angular - 将 Canvas 与 Angular Ionic 一起使用 - 难以保存附加文本的图像
- c++ - 在 while 循环中不被 cin 阻塞
- javascript - 错误域=NSURLErrorDomain 代码=-1001 “请求超时。” UserInfo={_NSURLErrorFailingURLSessionTaskErrorKey=LocalDataPDTask
- java - Spring Boot AuthenticationManagerBean 不起作用
- javascript - 使用 JS ID 作为 html 中的背景图片 url
- typescript - 在 TS 中,为什么 number[][number] === number?
- python - 使用 web3.py 解码智能合约的返回值?