如何使用Python Selenium查找网站中存在的特定元素?

2024-06-16 09:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

如何找出整个网站代码是否包含C10。 如果我们检查此元素,id=“ot-header-id-C10”,则此特定类别id为C10

    < > >其他网站可能不包含相同的突出显示的ID,但可能以C10结尾,我需要考虑网站中存在的C10或不存在。

  1. 下面的代码用于查找id=“ot-header-id-C10"

  2. 如何找到elementids或网站上包含C10的任何地方

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import time
from selenium.webdriver.support import expected_conditions as EC
import re
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By


fp = webdriver.FirefoxProfile()
capabilities = DesiredCapabilities().FIREFOX
capabilities["marionette"] = True

fp.set_preference("browser.cache.disk.enable", False)
fp.set_preference("browser.cache.memory.enable", False)
fp.set_preference("browser.cache.offline.enable", False)
fp.set_preference("network.http.use-cache", False) 
options = Options()
driver = webdriver.Firefox(desired_capabilities=capabilities, firefox_profile=fp)

url = "https://www.axe.com/nl"
driver.get(url)
time.sleep(4)
time_to_wait = 10
try:
    element = WebDriverWait(driver, time_to_wait).until(EC.presence_of_element_located((By.XPATH, "//h4[@id='ot-header-id-C10']")))
    print('Element with C10 attribute found')
    print(element)
except:
    print("C10 element not present")

Tags: fromimportidfalsecachetime网站selenium
2条回答

您可以这样做:

//*[contains(@id, 'C10') or contains(@class, 'C10')]

这基本上告诉您选择任何标记,即:spandivbutton,等等

如果它们有attributeidclass,基本上如果该属性包含C10

注意您可以在上面的xpath中使用or分隔的多个属性

这将为您提供一个明确指示,页面上是否有任何元素的属性中包含“C10”

elements = driver.find_elements_by_xpath("//*[contains(.,'C10')]")
if(elements):
    print("Elements containing C10 found on the page")

//*[contains(.,'C10')]将匹配任何属性中包含“C10”的任何元素。
driver.find_elements_by_xpath("//*[contains(.,'C10')]")将返回匹配web元素的列表。如果找到了这样的元素,列表将是非空的,非空列表在python中被解释为True

相关问题 更多 >