用urllib (python3)打开url挂起

2024-10-03 02:37:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用python3打开url:

import urllib.request
fp = urllib.request.urlopen("http://lebed.com/")

mybytes = fp.read()    
mystr = mybytes.decode("utf8")
fp.close()

print(mystr)

但它挂在第二行。 这个问题的原因是什么?如何解决?在


Tags: importcomhttpurlreadrequestutf8urllib
2条回答

我想原因是url不支持robot访问站点。您需要通过发送浏览器标题和请求来伪造浏览器访问

import urllib.request
url = "http://lebed.com/"
req = urllib.request.Request(
    url, 
    data=None, 
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
    }
)
f = urllib.request.urlopen(req)

在我的系统上试过这个,效果很好。在

同意Arpit Solanki。显示失败请求与成功请求的输出。在

Failed
    GET / HTTP/1.1
    Accept-Encoding: identity
    Host: www.lebed.com
    Connection: close
    User-Agent: Python-urllib/3.5

Success
    GET / HTTP/1.1
    Accept-Encoding: identity
    Host: www.lebed.com
    Connection: close
    User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36

相关问题 更多 >