【问题标题】:Get the full text of content intersected by a tag with Beautiful Soup使用 Beautiful Soup 获取标签相交的内容全文
【发布时间】:2020-01-10 02:43:37
【问题描述】:

假设我有一些类似下面的 HTML。

<p>This is the beginning of the text. <em>Italicized middle</em> This is the end of the text.</p>

这是一个标签,里面有另一个标签。我可以使用 Beautiful Soup 来获取它的内容:

list_of_tags = full_html.findAll()

for tag in list_of_tags:
    print(tag.find(text = True))

打印出来的:

This is the beginning of the text. 
Italicized middle

它切断了结尾部分——包含标签之后的所有内容。怎么才能找到那部分?

【问题讨论】:

  • 用一个简单的算法而不是用漂亮的汤来达到你想要的效果怎么样?
  • @Mox 你这是什么意思?你的意思是解析它并以不同的方式剥离标签吗?
  • BS 适用于解析 HTML——这不是问题。为什么不直接使用elem.text?这给出了整个文本内容,例如:print(BeautifulSoup('&lt;div&gt;a&lt;div&gt;b&lt;/div&gt;c&lt;/div&gt;', 'lxml').find('div').text) 打印 abc。否则,我有点不确定您实际上要在这里定位/生产什么。您是否需要将之前和之后以及子元素作为不同的实体?我认为 NavigableString 可能是你的朋友。
  • @ggorlen 好主意——我忘记了。这对于提取文本非常有用,但我试图在输出文件中保留斜体。 .text 方法不允许我判断文本最初位于 标记中。你知道这是否可能吗?
  • 当然。你到底想完成什么?只需将每个孩子放在p 中,并将&lt;em&gt;s 与纯文本节点或其他内容区分开来?

标签: python html web-scraping beautifulsoup


【解决方案1】:

感谢 ggorlen 的帮助,我修改了我的程序,使其工作方式有所不同。它首先修改标签的内容,使它们在标记中变为斜体(我认为这是为了我的目的而区分它的好方法。

for tag in tag_list:
    if tag.name == "em":
        tag.string.replace_with("*" + tag.string + "*")
    if tag.name == "strong":
        tag.string.replace_with("**" + tag.string + "**")

然后,在一个单独的循环中,我得到了不是我在上面修改的标签的所有内容的文本(否则它将是递归的),然后将其 .text 添加到列表中。

for tag in tag_list:
    if tag.name == "strong" || tag.name == "em":
        continue

    else:
        my_list.append(tag.text)

【讨论】:

  • 我不确定这是否是完成您想做的事情的最佳方式。如果您想提供有关替代品如何工作的更多详细信息,我可以提供答案。看起来您正在尝试转换为降价?
  • @ggorlen 是的,我想将其转换为降价。我使用了顶级答案here 中的一种方法来修改 标记中的文本。我的目标是从标签中获取所有文本,但仍然有办法知道子标签中的内容。
【解决方案2】:

如果想不分离地获取所有数据,可以使用以下方法。

from simplified_scrapy.simplified_doc import SimplifiedDoc 
html = '''<p>This is the beginning of the text. <em>Italicized middle</em> This is the end of the text.</p>
'''
doc = SimplifiedDoc(html)
print (doc.p.text)

结果:

This is the beginning of the text. Italicized middle This is the end of the text.

【讨论】:

    猜你喜欢
    • 2021-02-22
    • 2017-02-19
    • 2017-12-31
    • 2020-08-24
    • 2021-12-04
    • 2019-11-08
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    相关资源
    最近更新 更多