我正在使用Python和Selenium抓取某个网页的内容。当前,我遇到以下问题:存在多个具有相同名称的div类,但是每个div类具有不同的内容。我只需要一个特定的div类的信息。在以下示例中,由于链接文本中包含“重要元素”,因此我需要第一个“ show_result”类中的信息:

<div class="show_result">
    <a href="?submitaction=showMoreid=77" title="Go-here">
    <span class="new">Important-Element</span></a>
    Other text, links, etc within the class...
</div>

<div class="show_result">
    <a href="?submitaction=showMoreid=78" title="Go-here">
    <span class="new">Not-Important-Element</span></a>
    Other text, links, etc within the class...
</div>

<div class="show_result">
    <a href="?submitaction=showMoreid=79" title="Go-here">
    <span class="new">Not-Important-Element</span></a>
    Other text, links, etc within the class...
</div>


通过以下代码,我可以获得“重要元素”及其链接:
driver.find_element_by_partial_link_text('Important-Element')。但是,我还需要同一div类“ show-result”中的其他信息。如何在链接文本中引用整个包含重要元素的div类? driver.find_elements_by_class_name('show_result')不起作用,因为我不知道重要元素位于哪个div类中。

谢谢,
芬恩

编辑/更新:Ups,我使用xpath自己找到了解决方案:

driver.find_element_by_xpath("//div[contains(@class, 'show_result') and contains(., 'Important-Element')]")

最佳答案

我知道您已经找到了答案,但是我相信这是错误的,因为您还会选择其他节点,因为重要元素仍然位于非重要元素中。

也许它适用于您的特定情况,因为这并不是您要查找的文字。但是这里还有一些答案:


//div[@class='show_result' and starts-with(.,'Important-Element')]
//div[span[text()='Important-Element']]
//div[contains(span/text(),'Important-Element') and not(contains(span/text(),'Non'))]


有更多方法可以编写此内容...

09-30 16:35
查看更多