【问题标题】:web scraping... get everything withing a tag including other tags网络抓取...获取标签中的所有内容,包括其他标签
【发布时间】:2016-07-10 19:35:35
【问题描述】:

我有以下标签

<div class="example">
    <p> text <a href="#"> link </a> text</p>
</div>

我想得到

<p> text <a href="#"> link </a> text</p>

所以 div 中的所有内容都带有类示例。 我正在使用

from lxml import html
page = requests.get('X')
tree = html.fromstring(page.content)

description = tree.xpath('//div[@class="example"]/p//text()')

这给了我一个段落标签列表,然后我将它们与

结合在一起
description = ' '.join('<p>{0}</p>'.format(paragraph) for paragraph in description)

但是必须有一种方法可以直接获取 div 中的内容吗? 谢谢 卡尔

【问题讨论】:

    标签: html web-scraping lxml


    【解决方案1】:

    我找到了一个解决方案……不漂亮,但它给了我想要的东西……

    dummy = tree.xpath('//div[@class="example"]/div[2]/div/node()')   
    description = ''
    for paragraph in dummy:
        try:
            description += html.tostring(paragraph)
        except:
            pass
    

    【讨论】:

      【解决方案2】:

      你只需要获取标签内的所有节点:

      h = """<div class="example">
      <p> text <a href="#"> link </a> text</p>
      <p> othertext <a href="#"> otherlink </a> text</p>
      </div>"""
      
      from lxml import html
      
      x = html.fromstring(h)
      
      print("".join(html.tostring(n) for n in x.xpath("//div[@class='example']/*")))
      

      输出:

      <p> text <a href="#"> link </a> text</p>
      <p> othertext <a href="#"> otherlink </a> text</p>
      

      或使用.iterchildren:

      "".join(html.tostring(n) for n in x.xpath("//div[@class='example']")[0].iterchildren())
      

      也不需要任何尝试/除了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多