簡體   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