【发布时间】:2015-11-09 23:21:59
【问题描述】:
我在 Python2.7 中使用 Requests API。
我正在尝试通过代理服务器下载某些网页。我有一个可用代理服务器的列表。但并非所有代理服务器都能按预期工作。一些代理需要身份验证,其他代理需要重定向到广告页面等。为了检测/验证不正确的响应,我在我的 url 请求代码中包含了两项检查。看起来和这个很像
import requests
proxy = '37.228.111.137:80'
url = 'http://www.google.ca/'
response = requests.get(url, proxies = {'http' : 'http://%s' % proxy})
if response.url != url or response.status_code != 200:
print 'incorrect response'
else:
print 'response correct'
print response.text
有一些代理服务器的 requests.get 调用成功并且它们通过了这两个条件并且在 response.text 属性中仍然包含无效的 html 源。但是,如果我在我的 FireFox 浏览器中使用相同的代理并尝试打开相同的网页,我会显示一个无效的网页,但我的 python 脚本说响应应该是有效的。
有人可以指出我还缺少哪些其他必要的检查来清除不正确的 html 结果?
或
如何成功验证我打算接收的网页是否正确?
问候。
【问题讨论】:
-
尝试使用
urllib的代理,如此处Proxy with Urllib2 所做的那样 -
我使用 Requests 是因为我认为它更易于使用和理解。但是,我只是按照您的建议尝试使用 urllib2,结果是一样的。属性 response.url 和 response.code 返回与 Requests API 相同的值,并且 html 仍然无效。
标签: python html proxy response python-requests