Hel*_*nar 55 python scripting http httprequest http-head
通过使用python,我如何检查网站是否已启动?从我读到的,我需要检查"HTTP HEAD"并查看状态代码"200 OK",但该怎么做?
干杯
Ant*_*ney 86
您可以尝试使用要做到这一点getcode()
从urllib的
>>> print urllib.urlopen("http://www.stackoverflow.com").getcode()
>>> 200
Run Code Online (Sandbox Code Playgroud)
编辑:对于更现代的python,即python3
使用:
import urllib.request
print(urllib.request.urlopen("http://www.stackoverflow.com").getcode())
>>> 200
Run Code Online (Sandbox Code Playgroud)
cai*_*sah 18
我认为最简单的方法是使用Requests模块.
import requests
def url_ok(url):
r = requests.head(url)
return r.status_code == 200
Run Code Online (Sandbox Code Playgroud)
你可以使用httplib
import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD", "/")
r1 = conn.getresponse()
print r1.status, r1.reason
Run Code Online (Sandbox Code Playgroud)
版画
200 OK
Run Code Online (Sandbox Code Playgroud)
当然,只有这样www.python.org
.
import httplib
import socket
import re
def is_website_online(host):
""" This function checks to see if a host name has a DNS entry by checking
for socket info. If the website gets something in return,
we know it's available to DNS.
"""
try:
socket.gethostbyname(host)
except socket.gaierror:
return False
else:
return True
def is_page_available(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
False.
"""
try:
conn = httplib.HTTPConnection(host)
conn.request("HEAD", path)
if re.match("^[23]\d\d$", str(conn.getresponse().status)):
return True
except StandardError:
return None
Run Code Online (Sandbox Code Playgroud)
我使用requests来做到这一点,然后它既简单又干净。您可以定义和调用新函数(通过电子邮件等通知),而不是打印函数。Try- except块是必不可少的,因为如果主机无法访问,那么它将引发大量异常,因此您需要捕获所有异常。
import requests
URL = "https://api.github.com"
try:
response = requests.head(URL)
except Exception as e:
print(f"NOT OK: {str(e)}")
else:
if response.status_code == 200:
print("OK")
else:
print(f"NOT OK: HTTP response code {response.status_code}")
Run Code Online (Sandbox Code Playgroud)
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
req = Request("http://stackoverflow.com")
try:
response = urlopen(req)
except HTTPError as e:
print('The server couldn\'t fulfill the request.')
print('Error code: ', e.code)
except URLError as e:
print('We failed to reach a server.')
print('Reason: ', e.reason)
else:
print ('Website is working fine')
Run Code Online (Sandbox Code Playgroud)
适用于Python 3
您可以使用requests
库来查找网站是否已启动,status code
即200
import requests
url = "https://www.google.com"
page = requests.get(url)
print (page.status_code)
>> 200
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
96469 次 |
最近记录: |