Python, lxml - access text

天涯浪子 提交于 2020-01-14 16:35:20

问题


I m currently a bit out of ideas, and I really hope that you can give me a hint: Its probably best to explain my question with a small piece of sample code:

from lxml import etree
from io import StringIO

testStr = "<b>text0<i>text1</i><ul><li>item1</li><li>item2</li></ul>text2<b/><b>sib</b>"
parser = etree.HTMLParser()
# generate html tree
htmlTree   = etree.parse(StringIO(testStr), parser)
print(etree.tostring(htmlTree, pretty_print=True).decode("utf-8"))
bElem = htmlTree.getroot().find("body/b") 
print(".text only contains the first part: "+bElem.text+ " (which makes sense in some way)")
for text in bElem.itertext():
    print(text)

Output:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
  <body>
    <b>text0<i>text1</i><ul><li>item1</li><li>item2</li></ul>text2<b/><b>sib</b></b>
  </body>
</html>

.text only contains the first part: text0 (which makes sense in some way)
text0
text1
item1
item2
text2
sib

My Question:

I would like to access "text2" directly, or get a list of all text parts, only including the ones that can be found in the parent tag. So far I only found itertext(), which does display "text2".

Is there any other way I could retrieve "text2"?

Now you might be asking why I need this: Basically itertext() is pretty much already doing what I want:

  • Create a list, that contains all text found in an element's children
  • However, I want to process tables and lists that are encountered with a different function (which subsequently creates a list structure like this: ["text0 text1",["item1","item2"],"text2"] or for a table (1. Row with 1 Column, 2. Row with 2 Columns): ["1. row, 1 col",["2. row, 1. col","2. row, 2. col"]])

Maybe I m taking a completely wrong approach?


回答1:


You could just reimplement itertext() function and insert special handlers for ul, table if necessary:

from lxml import html

def itertext(root, handlers=dict(ul=lambda el: (list(el.itertext()),
                                                el.tail))):
    if root.text:
        yield root.text
    for el in root:
        yield from handlers.get(el.tag, itertext)(el)
    if root.tail:
        yield root.tail

print(list(itertext(html.fromstring(
                "<b>text0<i>text1</i><ul><li>item1</li>"
                "<li>item2</li></ul>text2<b/><b>sib</b>"))))

Output

['text0', 'text1', ['item1', 'item2'], 'text2', 'sib']

Note: yield from X could be replaced by for x in X: yield x on older than Python 3.3 versions.

To join adjacent strings:

def joinadj(iterable, join=' '.join):
    adj = []
    for item in iterable:
        if isinstance(item, str):
            adj.append(item) # save for later
        else:
            if adj: # yield items accumulated so far
                yield join(adj)
                del adj[:] # remove yielded items
            yield item # not a string, yield as is

    if adj: # yield the rest
        yield join(adj)

print(list(joinadj(itertext(html.fromstring(
                "<b>text0<i>text1</i><ul><li>item1</li>"
                "<li>item2</li></ul>text2<b/><b>sib</b>")))))

Output

['text0 text1', ['item1', 'item2'], 'text2 sib']

To allow tables, nested list in <ul> the handler should call itertext() recursively:

def ul_handler(el):
    yield list(itertext(el, with_tail=False))
    if el.tail:
        yield el.tail

def itertext(root, handlers=dict(ul=ul_handler), with_tail=True):
    if root.text:
        yield root.text
    for el in root:
        yield from handlers.get(el.tag, itertext)(el)
    if with_tail and root.tail:
        yield root.tail

print(list(joinadj(itertext(html.fromstring(
                    "<b>text0<i>text1</i><ul><li>item1</li>"
                    "<li>item2<ul><li>sub1<li>sub2</li></ul></ul>"
                    "text2<b/><b>sib</b>")))))

Output

['text0 text1', ['item1', 'item2', ['sub1', 'sub2']], 'text2 sib']


来源:https://stackoverflow.com/questions/11677411/python-lxml-access-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!