Gia*_* H. 5 python urllib2 reddit web-scraping http-status-code-504
尝试从 reddit 获取评论的 http 时遇到错误。这发生在各种 URL 上(并非所有 URL 都带有特殊字符),这就是其中之一。在一小时的时间范围内,可能会有 1000 个或更多的请求发送到 reddit.com 域。
hdr = {"User-Agent": "My Agent"}
try:
req = urllib2.Request("http://www.reddit.com/r/gaming/"
"comments/1bjuee/when_pok?©mon_was_good", headers=hdr)
htmlSource = urllib2.urlopen(req).read()
except Exception as inst:
print inst
Output>>HTTP Error 504: Gateway Time-out
Run Code Online (Sandbox Code Playgroud)
HTTP 错误 504 网关超时- 服务器(不一定是 Web 服务器)充当网关或代理来满足客户端(例如您的 Web 浏览器或我们的 CheckUpDown 机器人)访问请求的 URL 的请求。该服务器没有收到它访问的上游服务器的及时响应以处理您的 HTTP 请求。
这通常意味着上游服务器宕机(对网关/代理没有响应),而不是上游服务器和网关/代理不同意交换数据的协议。
问题可能出现在网络的不同位置,并且没有“唯一”的解决方案。您将不得不自己调查问题。
你的代码工作正常。您的问题可能的解决方案是:
import urllib2
hdr = {"User-Agent": "My Agent"}
while True:
try:
req = urllib2.Request("http://www.reddit.com/", headers=hdr)
response = urllib2.urlopen(req)
htmlSource = response.read()
if response.getcode() == 200:
break
except Exception as inst:
print inst
Run Code Online (Sandbox Code Playgroud)
此代码将尝试请求网页,直到获得 200 响应(成功 HTTP 请求的标准响应)。当循环中断时将发生 200 响应,您可以执行下一个请求(或您程序中的任何请求)