Python - Selenium Webdriver 找到一个元素,其中所有 div 节点都具有相似的名称

Python - Selenium Webdriver find an element where all the div nodes have similar names

我正在尝试访问 div,其中所有 div 都具有相同的名称。让我解释。我刚开始使用 selenium 和 python,我正试图抓取一个网页来学习。我运行陷入以下问题。我制作了示例 html 来显示网页的构建。所有 div 都具有完全相同的 class 和标题。然后是项目的 h1 标签和颜色的 p 标签(可点击 link)。当您给出某些指令时,我正在尝试搜索页面。示例:我正在寻找一辆白色赛车。我能够找到带有第一行代码的自行车,但是如何在赛车部分找到正确的颜色?如果我 运行 下面提到的 Python 我会收到一条错误消息。提前致谢!

<!DOCTYPE html>
<html>
    <body>
        <div class=div title=example>
            <h1>racebike</h1>
            <p class='test'>black</p>
        </div>
        <div class=div title=example>
            <h1>racebike</h1>
            <p class='test'>white</p>
        </div>
        <div class=div title=example>
            <h1>racebike</h1>
            <p class='test'>yellow</p>
        </div>
        <div class=div title=example>
            <h1>citybike</h1>
            <p class='test'>yellow</p>
        </div>
        <div class=div title=example>
            <h1>citybike</h1>
            <p class='test'>green</p>
        </div>
    </body>
</html>

test = (self.driver.find_element_by_xpath("//*[contains(text(), racebike)]"))
test.self.driver.find_element_by_xpath(".//*[contains(text(), white)]").click

要在 white racebike 元素上定位/click(),您需要为 element_to_be_clickable() 引入 WebDriverWait您可以使用以下任一项 based :

  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h1[text()='racebike']//following-sibling::p[@class='test' and text()='white']"))).click()
    
  • 使用 XPATH 考虑父 <div>:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='div' and @title='example']/h1[text()='racebike']//following-sibling::p[@class='test' and text()='white']"))).click()
    
  • 注意:您必须添加以下导入:

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

您可以使用您在解决方案中尝试过的相同 xpath。可能是服务器响应时间过长。

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

element = WebDriverWait(page, 10).until(EC.presence_of_element_located((By.XPATH, "//p[contains(@class, 'white')]")))
element.click()

多辆白色自行车

elements= WebDriverWait(driver, 30).until(EC.presence_of_all_elements_located((By.XPATH, "//p[contains(@class, 'white')]")))
for element in elements:
    element.click()