获取 http 状态代码 python selenium

get http status code python selenium

如果我打开link,如何获取python中的http状态码? 我是这样做的,但是即使页面抛出404错误,它也总是显示200...

from urllib.request import *

self.driver.get(link)
code = urlopen(link).getcode()
if not code == 200: 
  print('http status: ' + str(code))

这就是问题所在,Selenium 总能找到一个页面。您有 2 种方法来检查加载是否不起作用:

1 : 检查内容

self.assertFalse("<insert here a string which is only in the error page>" in self.driver.page_source)

2 : 使用 Django 测试客户端

response = self.client.get(link)
self.assertEqual(response.status_code,200)

编辑了您的示例。 尝试使用请求库。

from requests import get

self.driver.get(link)
request = get(link)
if not request.status_code == 200:
  print('http status: ' + str(request.status_code))

希望对您有所帮助。