【问题标题】:Python 3 get child elements (lxml)Python 3 获取子元素 (lxml)
【发布时间】:2019-03-17 04:55:58
【问题描述】:

我正在使用带有 html 的 lxml:

from lxml import html
import requests

如何检查元素的任何子元素是否具有 class= "nearby" 我的代码(本质上):

url = "www.example.com"
Page = requests.get(url)
Tree = html.fromstring(Page.content)
resultList = Tree.xpath('//p[@class="result-info"]')
i=len(resultList)-1 #to go though the list backwards
while i>0:
    if (resultList[i].HasChildWithClass("nearby")):
        print('This result has a child with the class "nearby"')

如何替换“HasChildWithClass()”以使其真正起作用?

这是一个示例树:

...
    <p class="result-info">
        <span class="result-meta">
            <span class="nearby">
                ... #this SHOULD print something
            </span>
        </span>
    </p>
    <p class="result-info">
        <span class="result-meta">
            <span class="FAR-AWAY">
                ... # this should NOT print anything
            </span>
        </span>
    </p>
...

【问题讨论】:

    标签: python html python-requests


    【解决方案1】:

    我试图了解您为什么使用lxml 来查找元素。不过BeautifulSoup 和re 可能是更好的选择。

    lxml = """
        <p class="result-info">
            <span class="result-meta">
                <span class="nearby">
                    ... #this SHOULD print something
                </span>
            </span>
        </p>
        <p class="result-info">
            <span class="result-meta">
                <span class="FAR-AWAY">
                    ... # this should NOT print anything
                </span>
            </span>
        </p>
        """
    

    但我做了你想要的。

    from lxml import html
    
    Tree = html.fromstring(lxml)
    resultList = Tree.xpath('//p[@class="result-info"]')
    i = len(resultList) - 1 #to go though the list backwards
    for result in resultList:
        for e in result.iter():
            if e.attrib.get("class") == "nearby":
                print(e.text)
    

    尝试使用bs4

    from bs4 import BeautifulSoup
    
    
    soup = BeautifulSoup(lxml,"lxml")
    result = soup.find_all("span", class_="nearby")
    print(result[0].text)
    

    【讨论】:

      【解决方案2】:

      这是我做的一个实验。

      在 python shell 中输入r = resultList[0] 并输入:

      >>> dir(r)
      ['__bool__', '__class__', ..., 'find_class', ...
      

      现在这种find_class 方法非常可疑。如果你查看它的帮助文档:

      >>> help(r.find_class)
      

      您将确认猜测。确实,

      >>> r.find_class('nearby')
      [<Element span at 0x109788ea8>]
      

      对于您提供的示例 xml 代码中的另一个标签 s = resultList[1],

      >>> s.find_class('nearby')
      []
      

      现在很清楚如何判断“附近”孩子是否存在。

      干杯!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-17
        • 1970-01-01
        • 2018-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多