Skip to main content
 首页 » 编程设计

python之服务不可用之urllib 代理不工作

2025年01月19日11think

我过去常常从谷歌获取信息,我知道我会在几次请求后被阻止,这就是我试图通过代理的原因。对于我使用的代理 来自此链接的 ProxyBroker: The Link

但是,如果我使用代理,谷歌会返回 503。如果我点击错误,谷歌会显示我的 IP 而不是代理 IP。

这是我尝试过的:

usedProxy = self.getProxy() 
if usedProxy is not None: 
    proxies = {"http": "http://%s" % usedProxy[0]} 
    headers = {'User-agent': 'Mozilla/5.0'} 
    proxy_support = urlrequest.ProxyHandler(proxies) 
    opener = urlrequest.build_opener(proxy_support, urlrequest.HTTPHandler(debuglevel=1)) 
    urlrequest.install_opener(opener) 
 
    req = urlrequest.Request(search_url, None, headers) 
    with contextlib.closing(urlrequest.urlopen(req)) as url: 
        htmltext = url.read() 

我尝试使用 http 和 https。

即使请求进展顺利,我也会收到带有以下消息的 503:

send: b'GET http://www.google.co.in/search?q=Test/ HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: www.google.co.in\r\nUser-Agent: Mozilla/5.0\r\nConnection: close\r\n\r\n' 
reply: 'HTTP/1.1 302 Found\r\n' 
header: Date header: Server header: Location header: Pragma header: Expires header: Cache-Control header: Content-Type header: Content-Length header: X-XSS-Protection header: X-Frame-Options header:  
 
>Connection send: b'GET http://ipv4.google.com/sorry/index?continue=http://www.google.co.in/search%3Fq%3DTest/&q=EgTCDs9XGMbOgNAFIhkA8aeDS0dE8uXKu31DEbfj5mCVdhpUO598MgFy HTTP/1.1\r\nAccept-Encoding: identity\r\nHost: ipv4.google.com\r\nUser-Agent: Mozilla/5.0\r\n 
 
>Connection: close\r\n\r\n' 
reply: 'HTTP/1.1 503 Service Unavailable\r\n' 

如果上面的错误没有发生,我最终得到如下错误:

>[Errno 54] Connection reset by peer 

我的问题是:

  1. 每次错误链接中的 IP 都是我的 IP 而不是代理 IP?

    Google Error Link

  2. 如果每次主机 IP 都显示在来自 google 的错误消息中并且问题来自代理,如何绕过错误?

请您参考如下方法:

Google 似乎知道我使用了代理,因为它使用 HTTPS 而 HTTPS 代理似乎不起作用。所以 HTTP 代理被检测到,这就是为什么我在 50-60 次查询后直接被阻止。

我的解决方案:

我尝试了在 Stackoverflow 上找到的所有解决方案,但它们无法像 sleep 10 秒那样正常工作。但是我发现了一篇有同样问题的文章,当时解决方案“相当”简单。首先我下载 fake-useragent来自 Python 的库,它提供了大量有用的用户代理。

我在每次请求时从这个列表中随机选择一个用户代理。我还添加了只接受普通用户代理的内容,否则页面会有不同的 HTML,不适合我的读取方法。

安装 Useragent 并随机选择一个后,我添加了 15 到 90 秒之间的休眠,因为文章作者尝试了不同的时间跨度,并在 30 秒后被阻止。因此,通过这两个简单的更改,我的程序成功运行了 10 小时,没有出现故障。

我希望这对您也有帮助,因为我花了很多时间才弄清楚谷歌何时会阻止您。所以它每次都简单检测,但让您使用此配置。

祝大家爬行顺利!

编辑:

该程序在被禁止之前会收到约 1000 个请求。