Python 3.x 如何知道页面是否脱机或没有响应?
我用Python编写了一个简单的代码,可以浏览存储在tuple中的几个网页。我们的目标是定期浏览这些页面,检查它们是否在线,是否有响应。示例代码:Python 3.x 如何知道页面是否脱机或没有响应?,python-3.x,selenium,selenium-webdriver,webdriver,python-requests,Python 3.x,Selenium,Selenium Webdriver,Webdriver,Python Requests,我用Python编写了一个简单的代码,可以浏览存储在tuple中的几个网页。我们的目标是定期浏览这些页面,检查它们是否在线,是否有响应。示例代码: from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expect
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = webdriver.Chrome()
links = ('https://stackoverflow.com/', 'https://stackexchange.com/')
while True:
for url in links:
try:
browser.get(url)
print('OK')
except Exception as e:
print('Not OK: {}'.format(e))
但是这段代码即使在脱机时也会打印“OK”,所以我想get()方法不会处理实际页面未到达时的任何异常
我曾考虑过使用WebDriverWait(浏览器,5)。直到(EC.presence\u of\u element\u located((By.ID,'some\u common\u ID'))
检查我是否已到达实际页面,但我的元组可能包含没有公共ID、类或元素的不同url地址
然后,我考虑扭转这种情况,使用WebDriverWait(浏览器,5)。直到(EC.presence\u of_element\u located((By.ID,'main frame error'))
离线时(在他们的“恐龙游戏”页面)在谷歌浏览器中搜索特定元素。
但是在这种情况下,每次成功到达元组中的页面时,脚本都必须等待5秒钟,这将不必要地减慢整个测试
我认为必须有一种更简单的方法来使用selenium浏览页面,并知道是否实际访问了该页面,但我还没有找到解决方案。selenium没有提供获取http状态代码的模块。因此,您需要使用另一个模块,例如
request
module。这里有一个类似的问题
如果您的用例想知道页面是否处于脱机状态或没有响应,您甚至不需要Selenium,只需使用requests.head()
方法,如下所示:
- 代码块:
import requests links = ['https://stackoverflow.com/', 'https://stackexchange.com/'] for link in links: print(requests.head(link))
- 控制台输出:
<Response [200]> <Response [200]>
注意:根据当前的实现,Selenium在调用
get()
方法时实际上也使用python请求模块。谢谢,这适用于我的用例。由于requests.head()返回响应对象,因此requests.head(link).status\u代码可以访问代码本身。