【问题标题】:Python: XPATH search within nodePython:节点内的 XPATH 搜索
【发布时间】:2018-03-15 13:53:34
【问题描述】:

我有一个看起来像这样(缩短)的 html 代码;

<div id="activities" class="ListItems">
<h2>Standards</h2>
        <ul>
                    <li>
                        <a class="Title" href="http://www.google.com" >Guidelines on management</a>
                        <div class="Info">
                            <p>
                                text
                            </p>
                                <p class="Date">Status: Under development</p>
                        </div>
                    </li>
        </ul>
</div>
<div class="DocList">
    <h3>Reports</h3>
        <p class="SupLink">+ <a href="http://www.google.com/test" >View More</a></p>
            <ul>
                <li class="pdf">
                    <a class="Title" href="document.pdf" target="_blank" >Document</a>
                    <span class="Size">
                        [1,542.3KB]
                    </span>
                    <div class="Info">
                                <p>
                                    text <a href="http://www.google.com" >Read more</a>
                                </p>
                        <p class="Date">
                            14/03/2018
                        </p>
                    </div>
                </li>
            </ul>
</div>

我正在尝试使用以下代码选择 'a class="Title"' 下的 'href=' 中的值:

def sub_path02(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    url2 = []
    for node in tree.xpath('//a[@class="Title"]'):
        url2.append(node.get("href"))

    return url2

但是我得到了两个返回,'div class="DocList"' 下的一个也返回了。

我正在尝试更改我的 xpath 表达式,以便我只能在节点内查看,但我无法让它工作。

有人可以帮助我了解如何在特定节点内“搜索”。我浏览了多个 xpath 文档,但似乎无法弄清楚。

【问题讨论】:

    标签: python html xpath


    【解决方案1】:

    使用//,您已经选择了文档中的所有a 元素。

    要在特定的div 中搜索,请尝试使用 // 指定父级,然后再次使用 //a 来查看 div 中的任何位置

    //div[@class="ListItems"]//a[@class="Title"]
    
    for node in tree.xpath('//div[@class="ListItems"]//a[@class="Title"]'):url2.append(node.get("href"))
    

    【讨论】:

    • 非常感谢 Ted,您可以在 StackOwerflow 上获得如此快速和准确的答案,真是太棒了
    • @user2873939 - 很高兴能提供帮助。当我还是一名开发人员时,Stack Overflow 的人帮助了我。现在我只是想帮助人们回来。您介意对我的帖子进行投票和/或将其标记为答案吗?
    【解决方案2】:

    试试这个 xpath 表达式以递归方式选择具有特定 id 的 div:

    '//div[@id="activities"]//a[@class="Title"]'
    

    所以:

    def sub_path02(url):
        page = requests.get(url)
        tree = html.fromstring(page.content)
        url2 = []
        for node in tree.xpath('//div[@id="activities"]//a[@class="Title"]'):
            url2.append(node.get("href"))
    
        return url2
    

    注意:

    选择 id 比选择 class 更好,因为 id 应该是唯一的(在现实生活中,有时会出现错误的代码同一个页面有多个相同的id,但是一个class可以重复N次)

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 2013-07-19
      • 2011-11-01
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      相关资源
      最近更新 更多