简体   繁体   English

使用lxml.html解析html

[英]Parsing html using lxml.html

I'm developing a Python scraper at scraperwiki.com and I need to parse a html page that containt the following: 我正在scraperwiki.com上开发一个Python scraper,我需要解析一个包含以下内容的html页面:

<div class="items">
  <div class="item">
       ItemLine1 ItemLine1 ItemLine1
       <br> 
       ItemLine2 ItemLine2 ItemLine2
 </div>
 <br>
</div>

What I'm doing now is: 我现在正在做的是:

import scraperwiki
import lxml.html

#.......................
raw_string = lxml.html.fromstring(scraperwiki.scrape(url_to_scrape))
my_line = ((raw_string.cssselect("div.items div.item")[0]).text)
print (my_line)

and it prints ItemLine1 ItemLine1 ItemLine1 only. 它只打印ItemLine1 ItemLine1 ItemLine1 When I change [0] to [1] it throws an exception. 当我将[0]更改为[1]时,它会抛出异常。

How do I scrape that? 我怎么刮这个? Should I use xpath? 我应该使用xpath吗?

XPath is the most straightforward solution: XPath是最直接的解决方案:

items = raw_string.cssselect('div.items div.item')

texts = [item.xpath('br[1]/preceding-sibling::node()') for item in items]

The XPath br[1] selects the first br child of div.item ; 中的XPath br[1]选择第一br的子div.item ; The preceding-sibling:: axis contains all nodes that occur before the first br ; preceding-sibling:: axis包含在第一个br之前出现的所有节点; node() selects every kind of node (text or elements) that are in that axis. node()选择该轴中的每种节点(文本或元素)。

If your larger goal is to split up the children of a node by br elements, you can take a few different approaches. 如果您的更大目标是通过br元素拆分节点的子节点,则可以采用一些不同的方法。 The reason this is so tricky is that elements like br and hr are badly designed markup. 这是如此棘手的原因是像brhr这样的元素是设计糟糕的标记。 Using a tree-like markup language like sgml, html, or xml, things that should be together should be grouped by a common parent element rather than split by a childless delimiter element. 使用像sgml,html或xml这样的树状标记语言,应该在一起的东西应该由一个共同的父元素分组,而不是由无子分隔符元素分割。

I'll expand your test case to demonstrate some more complex situations: 我将扩展您的测试用例以演示一些更复杂的情况:

html = """<div class="items">
  <div class="item">
   <br>
   ItemLine1 ItemLine1 ItemLine1
   <a href="">item</a>
   Itemline1-b
   <br> 
   <a class="z">item2</a>
   ItemLine2 ItemLine2 ItemLine2
   <br><br>
   Itemline3
 </div>
 <br>
</div>"""

doc = lxml.html.fromstring(html)
itemlist = doc.cssselect('div.items div.item')

The first approach is to simply get all nodes in the paragraph and split them into different lists by br . 第一种方法是简单地获取段落中的所有节点,并通过br将它们分成不同的列表。 If you use this approach, don't use the text and tail attributes of the ElementTree API because you will probably end up duplicating text. 如果使用此方法,请不要使用ElementTree API的texttail属性,因为您可能最终会复制文本。

def paras_by_br_nodes(parent):
    """Return a list of node children of parent (including text nodes) grouped by "paragraphs" which are delimited by <br/> elements."""
    paralist = []
    paras = []
    for node in parent.xpath('node()'):
        if getattr(node, 'tag', None) == 'br':
            paralist.append(paras)
            paras = []
        else:
            paras.append(node)
        paralist.append(paras)
        return paralist


print paras_by_br_nodes(itemlist[0])

This produces lists like so: 这会产生如下列表:

[['\n       '],
 ['\n       ItemLine1 ItemLine1 ItemLine1\n\t\t', <Element a at 0x10498a350>, '\n\t\tItemline1-b\n       '],
 [<Element a at 0x10498a230>, '\n       ItemLine2 ItemLine2 ItemLine2\n       '],
 [], 
 ['\n       Itemline3\n ']]

A second approach is to make use of the ElementTree API and keep text nodes in the text and tail attributes. 第二种方法是使用ElementTree API并将文本节点保留在texttail属性中。 The downside of this approach is that if there is no element to attach the text, we need to just include the text node. 这种方法的缺点是,如果没有要附加文本的元素,我们只需要包含文本节点。 This list of non-homogenous types is a bit more trouble to work with. 这个非同类型的列表使用起来有点麻烦。

def paras_by_br_text(parent):
    paralist=[]
    para=[parent.text]
    for item in parent:
        if item.tag=='br':
            paralist.append(para)
            para = [item.tail]
        else:
            para.append(item)
    paralist.append(para)
    return paralist

print paras_by_br_text(itemlist[0])

This produces a list like so. 这会产生一个这样的列表。 Note that in contrast to the previous list it only has text nodes nodes in the first position of the list. 请注意,与之前的列表相比,它只在列表的第一个位置具有文本节点节点。 This corresponds to the br.tail text or parent.text (which is text before the first element). 这对应于br.tail文本或parent.text (它是第一个元素之前的文本)。

[['\n       '],
 ['\n       ItemLine1 ItemLine1 ItemLine1\n\t\t', <Element a at 0x1042f5170>],
 [<Element a at 0x1042f5290>],
 [],
 ['\n       Itemline3\n ']]

I think the best approach is to introduce new elements. 我认为最好的方法是引入新元素。 This html is using br when it should be using p or some other container element. 当它应该使用p或其他容器元素时,这个html使用br So instead, let's fix the html and return a list of elements instead of a list of list of nodes: 所以相反,让我们修复html并返回一个元素列表而不是一个节点列表列表:

def paras_by_br(parent):
    paralist = []
    para = lxml.html.etree.Element('para')
    if parent.text:
        para.text = parent.text
    for item in parent:
        if item.tag=='br':
            paralist.append(para)
            para = lxml.html.etree.Element('para')
            if item.tail:
                para.text = item.tail
        else:
            para.append(item)
    return paralist

paralist = paras_by_br(itemlist[0])

print "\n--------\n".join(lxml.html.etree.tostring(para) for para in paralist)

This prints the following: 这打印出以下内容:

<para>
       </para>
--------
<para>
       ItemLine1 ItemLine1 ItemLine1
        <a href="">item</a>
        Itemline1-b
       </para>
--------
<para><a class="z">item2</a>
       ItemLine2 ItemLine2 ItemLine2
       </para>
--------
<para/>

See how items are grouped by a new para element, which doesn't exist in the original document. 查看项目如何按新的para元素分组,原始文档中不存在该元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM