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

问题描述 投票:0回答:1

我正在尝试访问所有div具有相同名称的div。让我解释。我刚开始使用Selenium和python,并且试图抓取一个网页只是为了学习。我遇到了以下问题。我制作了示例html来显示网页的构建。所有的div具有完全相同的类和标题。然后是该项的h1标签和颜色的p标签(这是可单击的链接)。当您提供某些说明时,我正在尝试搜索页面。示例:我正在寻找一辆白色的赛车。我可以找到带有第一行代码的自行车,但是如何在Racebike部分中找到正确的颜色?如果我运行下面提到的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
python selenium selenium-webdriver xpath webdriverwait
1个回答
0
投票

要在white racebike元素上定位/ click(),您需要为element_to_be_clickable()引入WebDriverWait,并且可以使用以下基于Locator Strategies中的任何一个:

  • 使用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()
    
  • Note:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
© www.soinside.com 2019 - 2024. All rights reserved.