Python 获取内容的全文,并将其与带有Beautiful Soup的标记相交

Python 获取内容的全文,并将其与带有Beautiful Soup的标记相交,python,html,web-scraping,beautifulsoup,Python,Html,Web Scraping,Beautifulsoup,假设我有一些HTML,如下所示 <p>This is the beginning of the text. <em>Italicized middle</em> This is the end of the text.</p> 上面印着: This is the beginning of the text. Italicized middle 它会将包含的标签后面的所有部分都切断。如何找到那个部分?多亏了戈伦的帮助,我修改了我的程序,使其工作

假设我有一些HTML,如下所示

<p>This is the beginning of the text. <em>Italicized middle</em> This is the end of the text.</p>
上面印着:

This is the beginning of the text. 
Italicized middle

它会将包含的标签后面的所有部分都切断。如何找到那个部分?

多亏了戈伦的帮助,我修改了我的程序,使其工作方式有所不同。它首先修改标记的内容,使它们在标记中用斜体表示(出于我的目的,我认为这是区分标记的好方法)

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)

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

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)

用一个简单的算法而不是用漂亮的汤来达到你想要的效果怎么样?@Mox这是什么意思?你是说用另一种方式解析它并剥离标记吗?BS适合解析HTML——这不是问题所在。为什么不直接用
elem.text
?这会给出整个文本内容,例如:
print(beautifulsou('abc','lxml')。find('div')。text)
prints
abc
。否则,我有点不确定您在这里实际查找/生成的内容。是否需要将前后元素和子元素作为不同的实体?我认为Navigablesting可能是您的朋友。@ggorlen好主意-我已经忘记了这一点。这对于提取文本非常有用,但我很抱歉试图在我的输出文件中保留斜体。使用.text方法不允许我判断文本最初是在标记中。你知道这是否可能吗?当然。但是你到底想做什么?只需将每个子项都放在
p
中,并将
与纯文本节点或其他内容区分开来?我很抱歉不确定这是否是执行您尝试执行的操作的最佳方式。如果您提供有关替换操作的更多详细信息,我可以提供一个答案。看起来您正在尝试转换为降价?@ggorlen是的,我想将其转换为降价。我使用了来自顶部答案的方法来修改标记中的文本。我的目标是获得所有来自标签的文本,但仍然可以知道子标签中的内容。
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.