【问题标题】:How can I search a specific element on the page for text using XPATH (Selenium);如何使用 XPATH (Selenium) 在页面上的特定元素中搜索文本;
【发布时间】:2022-01-25 12:58:03
【问题描述】:

我似乎找不到这样的例子。

我要做的是在页面上的特定 div 元素中搜索可能会更改的文本。

应该是这样的

<div id="coolId">
   <div>This</div>
   <div>Can</div>
   <div>Change depending on the iteration of the page</div>
</div>

在我的例子中,div coolID 将始终存在,但它的 inner div 和子元素中的文本会根据加载的页面迭代而改变,并且我只需要在这个coolID div和cool div中搜索某些术语的存在,因为我知道它会一直存在,并且我想尽可能多地指定搜索,以免潜在地污染结果页面上其他地方的其他文字。

在我的脑海中,我是这样看的(使用上面的例子):

"//div[@id='coolId', contains(text(), 'Change depending on the iteration of the page')]"

或类似的东西。

有人知道怎么做吗?

【问题讨论】:

    标签: python selenium web-scraping xpath


    【解决方案1】:

    我不完全确定您是否可以根据所有 3 个内部元素文本设置正确的 XPath。
    您显然可以根据其中一个唯一的内部文本定位外部divid = coolId,然后从中提取所有内部文本。

    the_total_text = driver.find_element_by_xpath("//div[@id and contains(.,'Change depending on the iteration of the page')]").text
    

    这会给你

    the_total_text = This Can Change depending on the iteration of the page
    

    【讨论】:

      【解决方案2】:

      你应该试试:

      div_element_with_needed_text = driver.find_element_by_xpath("//div[@id='coolId']/div[text()[contains(.,'Change depending on the iteration of the page')]]")
      

      【讨论】:

        【解决方案3】:

        考虑 HTML:

        <div id="coolId">
           <div>This</div>
           <div>Can</div>
           <div>Change depending on the iteration of the page</div>
        </div>
        

        要检索与父 &lt;div id="coolId"&gt; 相关的变量文本,您可以使用以下解决方案:

        • 使用xpath提取这个

          first_child_text = driver.find_element(By.XPATH, "//div[@id='coolId']//following::div[1]").text
          
        • 使用xpath提取可以

          second_child_text = driver.find_element(By.XPATH, "//div[@id='coolId']//following::div[2]").text
          
        • 使用xpath提取根据页面的迭代变化

          third_child_text = driver.find_element(By.XPATH, "//div[@id='coolId']//following::div[3]").text
          

        使用xpath从后代中提取所有文本:

          all_child_text = driver.find_element(By.XPATH, "//div[@id='coolId']").text
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多