使用python urlopen进行url查询

时间:2012-12-16 22:09:14

标签: python http url

对于网址查询也使用urlopen似乎很明显。我试过的是:

import urllib2
query='http://www.onvista.de/aktien/snapshot.html?ID_OSI=86627'
f = urllib2.urlopen(query)
s = f.read()
f.close()

但是,对于此特定的url查询,它会因HTTP错误403被禁止而失败 在我的浏览器中输入此查询时,它可以正常工作。 此外,当使用http://www.httpquery.com/提交查询时,它可以正常工作。

您是否有建议如何正确使用Python来获取正确的响应?

2 个答案:

答案 0 :(得分:3)

看起来它需要cookie ...(你可以使用urllib2),但是如果你这样做的话,更简单的方法就是使用requests

import requests
session = requests.session()
r = session.get('http://www.onvista.de/aktien/snapshot.html?ID_OSI=86627')

这通常是一种在Python中检索URL的更简单,压力更小的方法。

requests会自动为您存储和重复使用Cookie。创建一个会话在这里有点过分,但是当你需要向登录页面等提交数据,或者在网站上重复使用cookie等时,它们非常有用......

使用urllib2就像

import urllib2, cookielib

cookies = cookielib.CookieJar()
opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(cookies) )
data = opener.open('url').read()

答案 1 :(得分:2)

似乎主机禁止了urllib2默认用户代理。您只需提供自己的用户代理字符串:

import urllib2
url = 'http://www.onvista.de/aktien/snapshot.html?ID_OSI=86627'
request = urllib2.Request(url, headers={"User-Agent" : "MyUserAgent"})
contents = urllib2.urlopen(request).read()
print contents