首页 > 解决方案 > 尝试使用 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()

标签: pythonpython-3.xweb-scraping

解决方案


服务器拒绝来自非人类User-AgentHTTP 标头的查询。

只需选择浏览器的 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()

推荐阅读