如何使用Python selenium识别并点击网站上多个位置的文本?

eqqqjvef  于 2023-06-04  发布在  Python
关注(0)|答案(2)|浏览(639)

我有关键字“知道更多”(使用关键字,我发现XPath的,并执行像点击的行动)和网站有类似的话,如“知道更多”学生贷款,教育贷款等,这不是按钮,但他们是锚标签。现在我想使用XPATH单击“KnowMore”关键字,这是“学生贷款”,但学生贷款是在块中可用的。

<div class="content">
    <h5 class="mb-10">For Students</h5>
    <h3>Enabling a hassle-free learning journey with curated solutions</h3>
    <h4>#CampusPower #StudentLoan</h4>
    <ul class="bullet-list bullet-list-orange mb-20">
        <li>One stop solution for all your education needs</li>
        <li>Customised product bundles for the country of your choice</li>
        <li>Explore pre & post admission guidance</li>
        <li>Learn how to manage your money.</li>
        </ul>
    <a id="ga-ese-whatsnew-1" href="/campus-power/student" class="ic-btn ic-btn-gradient">Know More</a>
    </div>

我不想采用手工XPath,所以我使用了基于关键字XPath的代码,如下所示。

element = WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, f"//*[contains(text(), '{keyword}')]"))
        )
element.click()

它只点击网页上的第一个“了解更多”,这是另一笔贷款。如何点击“了解更多”为学生贷款任何帮助的建议是赞赏。谢谢。

hrysbysz

hrysbysz1#

试试这个XPath:

//h5[text()='For Students']//following::a[text()='Know More'][1]
gzszwxb4

gzszwxb42#

要单击For Students部分中的Know More链接,您可以首先找到带有文本***For Students***的元素,然后参考该WebElement,您可以使用以下locator strategies之一遍历HTML DOM,以找到为element_to_be_clickable()引入WebDriverWait的所需链接:

  • 使用 XPATHfollowing-sibling
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h5[text()='For Students']//following-sibling::a[1]"))).click()
  • 使用 XPATHfollowing
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h5[text()='For Students']//following::a[1]"))).click()
  • 使用 XPATHfollowing-sibling 以及文本 Know More
keyword = "Know More"
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h5[text()='For Students']//following-sibling::a[text()='{keyword}']"))).click()
  • 使用 XPATHfollowing 以及文本 Know More
keyword = "Know More"
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//h5[text()='For Students']//following::a[text()='{keyword}']"))).click()

*注意:需要添加以下导入:

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

更新

作为替代,您也可以使用以下locator strategy

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//li[text()='One stop solution for all your education needs']//following::a[text()='Know More']"))).click()

相关问题