我尝试从html页面上的一个主标签中提取所有内容(标签和文本)。例如:
`my_html_page = '''
<html>
<body>
<div class="post_body">
<span class="polor">
<a class="p-color">Some text</a>
<a class="p-color">another text</a>
</span>
<a class="p-color">hello world</a>
<p id="bold">
some text inside p
<ul>
<li class="list">one li</li>
<li>second li</li>
</ul>
</p>
some text 2
<div>
text inside div
</div>
some text 3
</div>
<div class="post_body">
<a>text inside second main div</a>
</div>
<div class="post_body">
<span>third div</span>
</div>
<div class="post_body">
<p>four div</p>
</div>
<div class="post">
other text
</div>
</body>
<html>'''`
我需要使用xpath("(//div[@class="post_body"])[1]"
):
`
<div class="post_body">
<span class="polor">
<a class="p-color">Some text</a>
<a class="p-color">another text</a>
</span>
<a class="p-color">hello world</a>
<p id="bold">
some text inside p
<ul>
<li class="list">one li</li>
<li>second li</li>
</ul>
</p>
some text 2
<div>
text inside div
</div>
some text 3
</div>
`
所有内部标记<div class="post_body">
我看了this topic,但没有帮助。
我需要在lxml中通过beautifulsoup解析器创建DOM。
import lxml.html.soupparser
import lxml.html
text_inside_tag = lxml.html.soupparser.fromstring(my_html_page)
text = text_inside_tag.xpath('(//div[@class="post_body"])[1]/text()')
我只能提取标签内的文字,但我需要用标签提取文字。
如果我尝试使用它:
for elem in text.xpath("(//div[@class="post_body"])[1]/text()"):
print lxml.html.tostring(elem, pretty_print=True)
我有错误:TypeError: Type '_ElementStringResult' cannot be serialized.
请帮助。
答案 0 :(得分:2)
您可以尝试这种方式:
import lxml.html.soupparser
import lxml.html
my_html_page = '''...some html markup here...'''
root = lxml.html.soupparser.fromstring(my_html_page)
for elem in root.xpath("//div[@class='post_body']"):
result = elem.text + ''.join(lxml.html.tostring(e, pretty_print=True) for e in elem)
print result
通过将父result
内的文本节点与所有子节点的标记组合构造的 <div>
变量。