繁体   English   中英

Python urllib2问题

[英]Python urllib2 problems

我有一个非常基本的脚本,可以使用Python urllib2下载网站。

在过去的六个月中,它一直表现出色,然后今天早上不再起作用了吗?

#!/usr/bin/python
import urllib2
proxy_support = urllib2.ProxyHandler({'http': 'http://DOMAIN\USER:PASS@PROXY:PORT/'})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)
translink = open('/tmp/trains.html' ,'w')
response = urllib2.urlopen('http://translink.com.au')
html = response.read()
translink.write(html)
translink.close()

我现在收到以下错误

Traceback (most recent call last):
  File "./gettrains.py", line 7, in <module>
    response = urllib2.urlopen('http://translink.com.au')
  File "/usr/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/usr/lib/python2.7/urllib2.py", line 407, in open
    response = meth(req, response)
  File "/usr/lib/python2.7/urllib2.py", line 520, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/lib/python2.7/urllib2.py", line 445, in error
    return self._call_chain(*args)
  File "/usr/lib/python2.7/urllib2.py", line 379, in _call_chain
    result = func(*args)
  File "/usr/lib/python2.7/urllib2.py", line 528, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 502: Proxy Error ( The HTTP message includes an unsupported header or an unsupported combination of headers.  )

我是Python新手,非常感谢您的帮助。

干杯

#!/usr/bin/python
import requests
proxies = {
"http": "http://domain\user:pass@proxy:port",
"https": "http:// domain\user:pass@proxy:port",
} 
html = requests.get("http://translink.com.au", proxies=proxies)
translink = open('/tmp/trains.html' ,'w')
translink.write(html.content)
translink.close()

尝试更改标题。 例如:

opener = urllib2.build_opener(proxy_support)
opener.addheaders = ([('User-Agent' , 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)')])
urllib2.install_opener(opener)

几天前我遇到了同样的问题。 我的代理不接受默认标头user-agent ='Python-urllib / 2.7'

为了简化一点,我会避免在python中进行代理设置,而只是让您的OS为您管理它。 您可以通过设置环境变量(例如在Linux中export http_proxy="your_proxy" )来完成此操作。 然后只需直接通过python抓取文件即可,您可以使用urllib2requests ,也可以考虑使用wget模块。

完全有可能对您的代理进行了一些更改,以转发带有最终目的地不再接受的标头的请求。 在这种情况下,您几乎无能为力。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM