问题
I want to extract sometext from the html code, but the following doesn't r eturn sometext, instead it return "\n". So how to get sometest?
a=html.fromstring("""
<p class="clearfix">
<i class="xueli"></i>
sometext
</p>
""")
a.find(".//i").getparent().text
回答1:
Instead of .text
, use text_content()
method:
In [5]: a.find(".//i").getparent().text_content().strip()
Out[5]: 'sometext'
Or, you can get to the following text sibling of the i
element:
In [6]: a.xpath(".//i/following-sibling::text()")[0].strip()
Out[6]: 'sometext'
来源:https://stackoverflow.com/questions/39832587/python-lxml-how-to-get-text-from-a-element-which-has-a-child-element