403试图从Python访问网页时的状态代码

2024-04-26 10:06:41 发布

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

我已经尝试过使用JSON,但无法真正阅读此页。你知道吗

这是我的python代码。我在其他网站上也试过,但在这个网站上它返回403。你知道吗

import urllib2

req = urllib2.Request('http://www.taringa.net/envivo/ajax.php')
response = urllib2.urlopen(req)
the_page = response.read()

print the_page

Tags: the代码importjsonhttpnet网站response
2条回答

最好使用requests。我试过你的剧本,得到了403的状态。这意味着它的访问是关闭的,无论出于什么原因,我不知道。你知道吗

您必须添加“User-Agent”头才能使其正常工作。你知道吗

Urllib代码:

req = urllib2.Request('http://www.taringa.net/envivo/ajax.php')
req.add_header('User-Agent', 'Mozilla')
resp = urllib2.urlopen(req)
print resp.code  # Gives 200.
print resp.read()  # Gives the HTML of the page.

我建议您使用requests,主要是因为它使这类东西变得非常简单。你知道吗

请求代码:

h = {'User-Agent':'Mozilla'}
requests.get('http://www.taringa.net/envivo/ajax.php', headers=h)

相关问题 更多 >