gpt4 book ai didi

带有 urllib 模块的 Python 程序

转载 作者:行者123 更新时间:2023-11-30 23:07:56 25 4
gpt4 key购买 nike

各位

下面的程序用于找出页面http://whatismyipaddress.com/中给出的IP地址

import urllib2
import re

response = urllib2.urlopen('http://whatismyipaddress.com/')

p = response.readlines()
for line in p:
ip = re.findall(r'(\d+.\d+.\d+.\d+)',line)
print ip

但我无法解决该问题,因为它给出了以下错误

Traceback (most recent call last):
File "Test.py", line 5, in <module>
response = urllib2.urlopen('http://whatismyipaddress.com/')
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 154, in urlopen
return opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 437, in open
response = meth(req, response)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 550, in http_response
'http', request, response, code, msg, hdrs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 475, in error
return self._call_chain(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 409, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 558, in http_error_default
raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)

urllib2.HTTPError:HTTP 错误 403:禁止

有人知道需要进行哪些更改才能消除错误并获得所需的输出吗?

最佳答案

http错误代码403告诉您服务器出于某种原因不想响应您的请求。在本例中,我认为它是您的查询的用户代理(urllib2 使用的默认值)。

您可以更改用户代理:

opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
response = opener.open('http://www.whatismyipaddress.com/')

然后你的查询就会起作用。

但不能保证这会继续有效。该网站可以决定阻止自动查询。

关于带有 urllib 模块的 Python 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31980793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com