如何使用 selenium (Python) 检测某个词是否出现在 Chrome 页面上?

How can I detect if a word is present on a Chrome page using selenium (Python)?

这是我的代码:

from selenium import webdriver
from selenium.webdriver.support.ui import Select
import random
import time
from selenium.common.exceptions import NoSuchElementException


driver = webdriver.Chrome()
driver.get("https://www.ti.com/store/ti/en/p/product/?p=CD4040BE&keyMatch=CD4040BE")
time.sleep(1)
accept_and_proceed = driver.find_element_by_xpath('//*[@id="consent_prompt_submit"]')
accept_and_proceed.click()

region = Select(driver.find_element_by_xpath('//*[@id="llc-cartpage-ship-to-country"]'))
region.select_by_visible_text('Italy')

continue1 = driver.find_element_by_xpath('//*[@id="llc-cartpage-ship-to-continue"]')
continue1.click()

网站上有Inventory这个词。 如何检测页面上是否存在单词 Inventory?如果它存在则打印 x 如果它不刷新页面直到它

试试这个:

if(driver.getPageSource().contains("Inventory"))
{
   
}

else
{
    driver = webdriver.Chrome()
    driver.get(response.url)   
    time.sleep(3)   
    driver.refresh()
}

要验证单词 Inventory 是否出现在页面上,您可以使用 try-except{} 块诱导 WebDriverWait for the and you can use the following :

代码块:

driver.get("https://www.ti.com/store/ti/en/p/product/?p=CD4040BE&keyMatch=CD4040BE")
Select(WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//select[@id='llc-cartpage-ship-to-country']")))).select_by_visible_text('Italy')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='llc-cartpage-ship-to-continue']"))).click()
while True:
    try:
        WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[contains(@class, 'u-tablet-up-only')]//span[@class='product-note product-availability' and contains(., 'Inventory')]")))
        print("x")
        break
    except TimeoutException:
        driver.refresh()
        continue
driver.quit()

控制台输出:

x

注意:您必须添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException

使用 SeleniumBase,您可以使用 self.assert_text(test)self.assert_text(text, selector) 方法断言页面上的文本(或者如果提供了第二个可选选择器参数,则断言元素中的文本)。您还可以使用方法:self.is_text_visible(text)self.is_text_visible(text, selector),其中 return True 或 False。

from seleniumbase import BaseCase

class DemoSiteTests(BaseCase):
    def test_demo_site(self):
        self.open("https://seleniumbase.io/demo_page")
        self.assert_text("Demo Page")
        self.assert_text("Demo Page", "h1")

这是一个使用这些的更长的示例:https://github.com/seleniumbase/SeleniumBase/blob/master/examples/test_demo_site.py