Python - 从URL获取头信息
我一直在到处寻找一个Python 3.x的代码示例,想获取HTTP头信息。
像PHP中的get_headers那样简单的功能,在Python中却很难找到。或者说,我可能不太清楚该怎么理解这个问题。
简单来说,我想写一个程序,能检查一个网址是否存在。
大概是这样的:
h = get_headers(url)
if(h[0] == 200)
{
print("Bingo!")
}
到目前为止,我尝试过:
h = http.client.HTTPResponse('http://docs.python.org/')
但总是出现错误。
4 个回答
2
对于 Python 2.x
这里可以使用 urllib、urllib2 或 httplib。不过要注意,urllib 和 urllib2 是基于 httplib 的。所以,如果你打算频繁进行这种检查(比如上千次),使用 httplib 会更好。更多的文档和示例可以在 这里找到。
示例代码:
import httplib
try:
h = httplib.HTTPConnection("www.google.com")
h.connect()
except Exception as ex:
print "Could not connect to page."
对于 Python 3.x
Python 3.x 中的 urllib2 和 http.client 库的情况和 Python 2.x 的 urllib(或 urllib2)和 httplib 类似。同样,http.client 应该会更快。想要获取更多文档和示例,可以查看 这里。
示例代码:
import http.client
try:
conn = http.client.HTTPConnection("www.google.com")
conn.connect()
except Exception as ex:
print("Could not connect to page.")
如果你想检查状态码,你需要把
conn.connect()
替换为
conn.request("GET", "/index.html") # Could also use "HEAD" instead of "GET".
res = conn.getresponse()
if res.status == 200 or res.status == 302: # Specify codes here.
print("Page Found!")
注意,在这两个示例中,如果你想捕获特定的异常,比如当 URL 不存在时,而不是捕获所有异常,可以改为捕获 socket.gaierror 异常(详细信息请查看 socket 文档)。
3
你可以使用requests模块来检查这个内容:
import requests
url = "http://www.example.com/"
res = requests.get(url)
if res.status_code == 200:
print("bingo")
在下载整个网页内容之前,你还可以通过使用头部信息来查看一些头部内容。
11
要在 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
对象 也能让你访问所有的头信息。例如:
>>> response.getheader('Server')
'Apache/2.2.16 (Debian)'
如果调用 urllib.request.urlopen()
失败,会抛出一个 HTTPError
异常
。你可以处理这个异常来获取响应代码:
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()))