【问题标题】:Python selenium how to check if a specific web element contains a specific keyword?Python selenium如何检查特定的Web元素是否包含特定的关键字?
【发布时间】:2020-08-23 06:52:56
【问题描述】:

试图检查页面上是否有特定的 div 类:

<div class="css-1dbjc4n">

包含特定关键字,例如“instagram.com”

我目前的代码是:

Search = driver.find_elements_by_xpath("//*[contains(text(), 'instagram.com')]")
if len(search) > 0:
    print("Found what I was looking for")

上面代码的问题是它搜索整个页面,我需要它只搜索一个特定的网络元素。

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver


    【解决方案1】:

    您可以使用 WebElement.find_Emement_by_xpath 方法。如下所示。

    ele = driver.find_element_by_class_name("css-1dbjc4n") #Webelement for div
    result = ele.find_elements_by_xpath(".//*[text()='instagram.com']")
    if len(result)>0:
        print('You found total {} occurance'.format(len(result)))
    

    现在,它将在类css-1dbjc4n的div内打印带有文本instagram.com的元素总数

    【讨论】:

      【解决方案2】:

      您只需更改您正在使用的 XPath 即可完成此操作!

      search = driver.find_elements_by_xpath("//div[@class='css-1dbjc4n']//div[contains(text(), 'instagram.com')]")
      if len(search) > 0:
          print("Found what I was looking for")
      

      【讨论】:

        【解决方案3】:

        driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")

        【讨论】:

          猜你喜欢
          • 2013-07-31
          • 2022-12-18
          • 1970-01-01
          • 2015-12-19
          • 1970-01-01
          • 2023-04-10
          • 1970-01-01
          • 2020-06-18
          • 2015-05-15
          相关资源
          最近更新 更多