Python erhält den Statuscode der HTTP-Anfrage (200, 404 usw.)
欧阳克
欧阳克 2017-06-28 09:25:31
0
2
1130

Python ruft den Statuscode der HTTP-Anfrage (200, 404 usw.) ab, ohne auf den gesamten Quellcode der Seite zuzugreifen, was eine Verschwendung von Ressourcen darstellt:

输入:segmentfault.com 输出:200
输入:segmentfault.com/nonexistant 输出:404
欧阳克
欧阳克

温故而知新,可以为师矣。 博客:www.ouyangke.com

Antworte allen(2)
ringa_lee

参考文章:Python实用脚本清单

http不只有get方法(请求头部+正文),还有head方法,只请求头部

import httplib

def get_status_code(host, path="/"):
    """ This function retreives the status code of a website by requesting
        HEAD data from the host. This means that it only requests the headers.
        If the host cannot be reached or something else goes wrong, it returns
        None instead.
    """
    try:
        conn = httplib.HTTPConnection(host)
        conn.request("HEAD", path)
        return conn.getresponse().status
    except StandardError:
        return None
        
print get_status_code("segmentfault.com") # prints 200
print get_status_code("segmentfault.com", "/nonexistant") # prints 404
刘奇

你用get请求就会请求整个头部+正文, 可以试下head方法, 直接访问头部!

import requests
html = requests.head('http://segmentfault.com')    # 用head方法去请求资源头部
print html.status_code  # 状态码

html = requests.head('/nonexistant')   # 用head方法去请求资源头部
print html.status_code   # 状态码

# 输出:
200
404
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage