最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】Python中urllib2.urlopen打开某个url的request出现未知错误–>传入urllib2.Request的url需要是string,不能是unicode

Python crifan 3120浏览 0评论

【问题】

当前已经是可以登陆百度空间,已经有了对应的cookie信息了,是通过cookiejar管理的。

登陆空间后,用:

try :
    req = urllib2.Request(url);
    req.add_header('User-Agent', gConst['userAgentIE9']);
    req.add_header('Cache-Control', 'no-cache');
    req.add_header('Accept', '*/*');
    req.add_header('Connection', 'Keep-Alive');
    resp = urllib2.urlopen(req);
except urllib2.URLError,reason :
    logging.warning("  URLError when open %s, reason=%s", url, reason)
except urllib2.HTTPError,code :
    logging.warning("  HTTPError when open %s, code=%s", url, code)
except :
    logging.warning("  Unknown error when open %s", url)

去打开某个网页,结果在urllib2.urlopen的位置出错,并且是unknown error:

LINE 1584 : INFO     [0001] http://hi.baidu.com/%D7%CA%C1%CF%CA%D5%BC%AF/blog/item/d1eab626e24c09168a82a191.html

begin to process:  http://hi.baidu.com/%D7%CA%C1%CF%CA%D5%BC%AF/blog/item/d1eab626e24c09168a82a191.html

LINE 1619 : WARNING    Unknown error when open http://hi.baidu.com/%D7%CA%C1%CF%CA%D5%BC%AF/blog/item/d1eab626e24c09168a82a191.html

LINE 2987 : ERROR    Unknown Error !

而不是原以为的某个种URLError。

【解决过程】

1.以为是代码写的有问题了。但是,经过测试,同样的代码,去打开别的百度空间,登陆后,访问空间内第一个帖子的url,都是可以的,就是登陆:

HiBaiduToWordpress_v2012-03-16-office.py -s http://hi.baidu.com/资料收集 -z modifyPost -d modifiedPostPattern_greenwaste.txt -u greenwaste -p xxx

有问题,会出错。

2.后来手动把原先的url:

http://hi.baidu.com/%D7%CA%C1%CF%CA%D5%BC%AF/blog/item/d1eab626e24c09168a82a191.html

改为:

http://hi.baidu.com/资料收集/blog/item/d1eab626e24c09168a82a191.html

结果却可以正常打开了,所以看起来好像是地址有误。

猜测是,传入的url是UTF-8或者别的格式的,导致地址不是百度所期望的GB18030的,所以地址打开出错。

3.后来经过调试,发现原因了,因为此处获得的url,是unicode类型:

type(url)= <type ‘unicode’>

导致调用urllib2.urlopen的时候出错,而如果传入的url是string类型:

type(url)= <type ‘str’>

那么再调用urllib2.urlopen就不会出错了。

对应的,去看了Python的手册中关于urllib2.urlopen和urllib2.Request的解释:

class urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])

This class is an abstraction of a URL request.

url should be a string containing a valid URL.

urllib2.urlopen(url[, data][, timeout])

Open the URL url, which can be either a string or a Request object.

即,对于urllib2.Request传入的url应该是string,而不能是unicode,否则即使urllib2.Request没出错,到了后面的urllib2.urlopen也会出错的。

【总结】

对于调用urllib2.Request和urllib2.urlopen,之前从来没有注意过,原来传入的url,应该是string类型的而不能是unicode

否则,传入的url是unicode的话,对于:

req = urllib2.Request(url);

resp = urllib2.urlopen(req);

的形式,即使urllib2.Request不出错,那么后面的urllib2.urlopen也会出错的。

转载请注明:在路上 » 【已解决】Python中urllib2.urlopen打开某个url的request出现未知错误–>传入urllib2.Request的url需要是string,不能是unicode

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.153 seconds, using 22.13MB memory