我一直在四处寻找 Python 3.x 代码示例来获取 HTTP header 信息。
在 Python 中不容易找到像 PHP 中的 get_headers 等价物这样简单的东西。或者我不确定如何最好地解决这个问题。
本质上,我想编写一些可以查看 URL 是否存在的代码
行内的事
h = get_headers(url)
if(h[0] == 200)
{
print("Bingo!")
}
到目前为止,我已经尝试过了
h = http.client.HTTPResponse('http://docs.python.org/')
但总是报错
最佳答案
获取 python-3.x 中的 HTTP 响应代码, 使用 urllib.request
模块:
>>> import urllib.request
>>> response = urllib.request.urlopen(url)
>>> response.getcode()
200
>>> if response.getcode() == 200:
... print('Bingo')
...
Bingo
返回的HTTPResponse
Object也将使您可以访问所有 header 。例如:
>>> response.getheader('Server')
'Apache/2.2.16 (Debian)'
如果调用urllib.request.urlopen()
失败,一个 HTTPError
Exception
被引发。您可以处理此问题以获取响应代码:
import urllib.request
try:
response = urllib.request.urlopen(url)
if response.getcode() == 200:
print('Bingo')
else:
print('The response code was not 200, but: {}'.format(
response.get_code()))
except urllib.error.HTTPError as e:
print('''An error occurred: {}
The response code was {}'''.format(e, e.getcode()))
关于Python - 从 URL 获取标题信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14949644/