我想知道是否有人可以帮助我了解如何使用 BeautifulSoup 和 Python 获取网站抓取并将其转换为文本文件。它来自留言板,人们可以在留言板上写下自己的文字,有时还会引用以前的留言。
我可以毫无问题地抓取文本,但我不知道如何处理引用的文本(由
元素表示)。我希望它们在我的文本输出中缩进。可以有简单的块引用,也可以有嵌套的块引用。我不知道嵌套的块引用可能有多深。这是一个例子:
标题
这是引用1一些文字
这是引用2 这是嵌套在引用 2 中的引用 3
更多文字
我想要创建的输出文本是:
标题 ---这是引用1 一些文字 ——这是引用2 ----这是引用 3 嵌套在引用 2 中 更多文字
关于如何用 Python 进行编程有什么想法吗?任何帮助将不胜感激,谢谢!
我尝试过使用 get_text() 但它不区分常规文本和块引用文本。
您可以通过迭代元素树的递归函数来实现此目的,如下所示:
from bs4 import BeautifulSoup
html = """
<p>
Title
</p>
<blockquote>
This is quote 1
</blockquote>
<p>
Some text
<blockquote>
This is quote 2
<blockquote>
This is quote 3 nested in quote 2
</blockquote>
</blockquote>
</p>
<p>
More text
</p>
""".replace('\n', '')
soup = BeautifulSoup(html)
def print_text_with_blockquote_indents(tag, prefix=""):
# Add '--' prefix if this tag is a blockquote
if tag.name == 'blockquote':
prefix = prefix + '--'
# Print the inner text of this tag only
print(f"{prefix} {''.join(tag.find_all(string=True, recursive=False))}")
# Continue recursively if the tag has children
all_children = tag.find_all(recursive=False)
if len(all_children) > 0:
for tag in all_children:
print_text_with_blockquote_indents(tag, prefix)
print_text_with_blockquote_indents(soup)
函数
print_text_with_blockquote_indents
迭代元素树,打印每个标签的内部文本,并仅当标签名称为“blockquote”时才将前缀“--”附加到该标签和所有子标签的文本。
输出:
Title
-- This is quote 1
Some text
-- This is quote 2
---- This is quote 3 nested in quote 2
More text
如果您有任何疑问,请告诉我。