python urllib2: 连接被对方重置

10 投票
4 回答
20341 浏览
提问于 2025-04-16 18:32

我有一个用perl写的程序,它可以从我大学图书馆的数据库中获取数据,运行得很好。现在我想用python重写这个程序,但遇到了一个问题:<urlopen error [errno 104] connection reset by peer>

这是我用perl写的代码:

    my $ua = LWP::UserAgent->new;
    $ua->cookie_jar( HTTP::Cookies->new() );
    $ua->timeout(30);
    $ua->env_proxy;
    my $response = $ua->get($url); 

这是我写的python代码:

    cj = CookieJar();
    request = urllib2.Request(url); # url: target web page 
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj));
    opener = urllib2.install_opener(opener);
    data = urllib2.urlopen(request); 

我在家里通过VPN(虚拟私人网络)登录我大学的图书馆,我试过用perl代码和python代码。perl代码按我预期的那样工作,但python代码总是出现“urlopen error”的错误。

我在网上查了一下这个问题,似乎是urllib2无法加载环境代理。但根据urllib2的文档,urlopen()函数在不需要身份验证的代理下应该是可以正常工作的。现在我感到很困惑。有没有人能帮我解决这个问题?

4 个回答

1

你可能会发现,requests模块比urllib2更容易使用。

2

首先,正如Steve所说,你需要使用response.read(),但这并不是你的问题所在。

import urllib2
response = urllib2.urlopen('http://python.org/')
html = response.read()

你能详细说说错误的情况吗?你可以这样获取错误信息:

try:
    urllib2.urlopen(req)
except URLError, e:
     print e.code
     print e.read()

来源:http://www.voidspace.org.uk/python/articles/urllib2.shtml

(我把这个放在评论里,但它把我的换行符给吃掉了)

9

我按照Uku Loskit和Mikko Ohtamaa的建议,尝试伪装了用户代理头,结果解决了我的问题。代码如下:

    proxy = "YOUR_PROXY_GOES_HERE"
    proxies = {"http":"http://%s" % proxy}
    headers={'User-agent' : 'Mozilla/5.0'}
    proxy_support = urllib2.ProxyHandler(proxies)
    opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
    urllib2.install_opener(opener)

    req = urllib2.Request(url, None, headers)
    html = urllib2.urlopen(req).read()
    print html

希望对其他人也有帮助!

撰写回答