gpt4 book ai didi

python - 如何在 Python 中获取两个 html 标签之间的所有内容?

转载 作者:太空宇宙 更新时间:2023-11-04 03:34:03 25 4
gpt4 key购买 nike

我尝试从 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.

请帮忙。

最佳答案

你可以这样试试:

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>带有所有子节点的标记。

关于python - 如何在 Python 中获取两个 html 标签之间的所有内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29919753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com