【问题标题】:How to find an element which its two childs match with two different values?如何找到它的两个子元素与两个不同的值匹配的元素?
【发布时间】:2019-06-12 11:06:18
【问题描述】:

我想使用 Python selenium 在 Speedtest 网站上查找特定服务器。例如,我想查找其 host-locationDagupan Cityhost-sponsorUSATV One Inc。 下面是html代码的样子。里面会有很多相同的类名。我应该怎么做才能匹配这两个不同的值? 谢谢!

<ul data-view-name="serverCollection" data-view-cid="view34" class=""><li data-model-cid="c184">
  <a data-server-id="11886" data-https-host="1">
      <span class="host-location">
        Dagupan City
      </span>
      <span class="host-sponsor">
        USATV One Inc
      </span>


  </a>
</li><li data-model-cid="c185">
  <a data-server-id="25314" data-https-host="1">
      <span class="host-location">
        Park City, Utah
      </span>
      <span class="host-sponsor">
        Utah Broadband
      </span>


  </a>
</li><li data-model-cid="c186">
  <a data-server-id="14515" data-https-host="1">
      <span class="host-location">
        Nagaoka
      </span>
      <span class="host-sponsor">
        CanopusAzusa
      </span>


  </a>
</li><li data-model-cid="c187">
  <a data-server-id="14890" data-https-host="1">
      <span class="host-location">
        Jakarta
      </span>
      <span class="host-sponsor">
        PT. Aplikanusa Lintasarta
      </span>


  </a>
</li></ul>

【问题讨论】:

    标签: python selenium xpath webdriverwait xpath-1.0


    【解决方案1】:

    类似:

    //a[span[@class='host-location' and contains(text(),'Dagupan City')] and span[@class='host-sponsor' and contains(text(),'USATV One Inc')]]
    

    演示:

    参考资料:

    【讨论】:

    • 我使用“find_elements_by_xpath”来实现你的代码并且它有效!但是,它会得到一个包含两个元素的列表。这正常吗?我在我的网站上找不到其他元素。
    • a[contains(., 'Dagupan City') and contains(., 'USATV One Inc')] 不也能正常工作吗?
    【解决方案2】:

    你也可以试试

    //span[@class='host-sponsor'][contains(text(),'USATV One Inc')]/parent::a/span[contains(text(),'Dagupan City')]/parent::a
    

    【讨论】:

      【解决方案3】:

      查找与其子级有关的服务器class 属性 host-location 例如Dagupan Cityhost-sponsor 例如USATV One Inc由于元素是动态元素,您需要为所需元素诱导WebDriverWait,您可以使用以下Locator Strategy

      • XPath

        element = WebDriverWait(driver,15).until(lambda driver: driver.find_element_by_xpath("//a[span[@class='host-location' and contains(.,'Dagupan City')]]") and driver.find_element_by_xpath("//a[span[@class='host-sponsor' and contains(.,'USATV One Inc')]]"))
        

      【讨论】:

        猜你喜欢
        • 2015-08-06
        • 2011-03-02
        • 1970-01-01
        • 2015-10-05
        • 1970-01-01
        • 2019-09-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多