Python 的 urllib2 在某些站点上不起作用 [英] Python's urllib2 doesn't work on some sites

查看:26
本文介绍了Python 的 urllib2 在某些站点上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现您无法使用 Python 的 urllib2(或 urllib)从某些站点读取数据.一个例子...

I found that you can't read from some sites using Python's urllib2(or urllib). An example...

urllib2.urlopen("http://www.dafont.com/").read()
# Returns ''

当您使用浏览器访问网站时,这些网站会正常工作.我什至可以使用 PHP 抓取它们(没有尝试其他语言).我在其他网站上看到过同样的问题 - 但目前不记得网址.

These sites work when you visit the site with a browser. I can even scrape them using PHP(didn't try other languages). I have seen other sites with the same issue - but can't remember the URL at the moment.

我的问题是...

  1. 这个问题的原因是什么?
  2. 有什么解决方法吗?

推荐答案

我相信它会被用户代理阻止.您可以使用以下示例代码更改 User-Agent:

I believe it gets blocked by the User-Agent. You can change User-Agent using the following sample code:

USERAGENT = 'something'
HEADERS = {'User-Agent': USERAGENT}

req = urllib2.Request(URL_HERE, headers=HEADERS)
f = urllib2.urlopen(req)
s = f.read()
f.close()

这篇关于Python 的 urllib2 在某些站点上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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