我如何验证在UI中显示的标签(仅为5秒),并在使用selenium python的页面加载出现错误时出现?



如果我加载一个页面,在页面中有一些错误,将会有一个消息出现5到10秒的消息"更新数据错误"。如何检查页面加载时是否存在此错误?开发人员给了我这个标签的id,它以span开头。

我希望检查这个标签是否发生在页面加载使用硒和python。基本上检查在加载页面时是否有任何错误。我们有大约20到30个页面,所以必须检查每个页面加载没有任何错误

更新数据出错

如果你想检查多个页面,这实际上取决于你想检查的页面列表的类型。

如果是一个页面列表,例如"https://qwant.com"然后"https://duckduckgo.com"您可能希望在循环中遍历它们,每次迭代都有一个唯一的.get请求。在本例中,这取决于您如何存储链接列表。如果它在一个简单的列表中,你可以很容易地对列表中的每个url使用.get。假设您有一个存储在"url"中的链接列表。列表。所以:

# Your urls list
urls = ["https://qwant.com", "https://duckduckgo.com", "https://startpage.com"]

然后用for循环遍历列表中的每个链接:

for url in urls:
driver.get(url)
# Do the actions that you need here

现在进行消息id检查。您没有提供ID,因此我不确定该ID是简单ID还是XPath。但是,你可以根据你有哪一个来使用这两种方法。我们当然希望等待,看看消息是否会在页面上弹出。但是,需要注意的是,如果消息没有出现,您将获得TimeoutException,程序将被终止。为了防止这种情况,您可以使用try和except来查看消息是否出现。

要做到这一点,首先你需要引入一个WebDriverWait,其中指定了Selenium在寻找元素之前应该等待的时间。我们可以这样定义WebDriverWait:

wait = WebDriverWait(driver, 20)

在这种情况下"driver"是你在上面代码中定义的WebDriver的名字。

则需要等待该元素出现。您将使用新的wait方法来等待它出现。如果是一个简单的ID,您可以这样做:

wait.until(ec.presence_of_element_located((By.ID, "element-id")))

您提到ID包含span,这使我相信您可能得到了一个XPath标识符。如果是这种情况,只需修改代码以搜索具有该ID的XPath:

wait.until(ec.presence_of_element_located((By.XPATH, "//span[@id="element-id"]")))

但是,如果错误框中的文本是唯一的,并且您不确定ID,您也可以搜索错误本身的文本:

wait.until(ec.presence_of_element_located((By.XPATH, "//span[contains(text(), 'Error updating data')]")))

现在,正如我在开头提到的,因为你应该检查是否存在错误,所以有时它可能不存在。为了防止TimeoutException发生,您需要将代码包装在try/except语句中,以检查它是否实际存在,如果不存在则跳过它。所以你可以这样做:

try:
wait.until(ec.presence_of_element_located((By.XPATH, "//span[contains(text(), 'Error updating data')]")))
except TimeoutException:
pass

但是需要注意的是,要使其工作,您的项目需要导入Selenium Exceptions库,如下所示:

from selenium.common.exceptions import WebDriverException, TimeoutException

这同样适用于我们在开始使用的WebDriverWait,它将是:

from selenium.webdriver.support.ui import WebDriverWait

有了这些,你的最终代码可能看起来像这样:

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
from selenium.common.exceptions import TimeoutException
# Define WebDriver and WebDriverWait here
driver = webdriver.Firefox(executable_path="/geckdriver")
wait = WebDriverWait(driver, 20)
# Your urls list
urls = ["https://qwant.com", "https://duckduckgo.com", "https://startpage.com"]
# Iterate through every page in the urls list
for url in urls:
driver.get(url)
try:
wait.until(ec.presence_of_element_located((By.XPATH, "//span[contains(text(), 'Error updating data')]")))
print(f"Error code found on page {url}")
except TimeoutException:
pass

最新更新