使用 urllib (python3) 挂在打开的 url 上 [英] hangs on open url with urllib (python3)

查看:52
本文介绍了使用 urllib (python3) 挂在打开的 url 上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用 python3 打开 url:

I try to open url with python3:

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

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

print(mystr)

但它挂在第二行.此问题的原因是什么以及如何解决?

But it hangs on second line. What's the reason of this problem and how to fix it?

推荐答案

我猜是url不支持robot访问站点的原因.您需要通过随请求一起发送浏览器标头来伪造浏览器访问

I suppose the reason is that the url does not support robot visiting a site visit. You need to fake a browser visit by sending browser headers along with your request

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)

在我的系统上试过这个,它有效.

Tried this one on my system and it works.

这篇关于使用 urllib (python3) 挂在打开的 url 上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆