首页 文章

Python:节点内的XPATH搜索

提问于
浏览
0

我有一个看起来像这样(缩短)的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文档,但我似乎无法弄明白 .

2 回答

  • 0

    使用 // ,您已经选择了文档中的所有 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"))
    
  • 0

    尝试使用此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比一个类更好,因为id应该是唯一的(在现实生活中,有时在同一页面中有多个相同id的坏代码,但是一个类可以重复N次)

相关问题