Python - Beautifulsoup,使用内部标签区分 html 元素内的已解析文本

Python - Beautifulsoup, differentiate parsed text inside of an html element by using internal tags

所以,我正在开发一个 html 解析器,以从列表中提取一些文本数据并在给出输出之前对其进行格式化。我有一个需要设置为粗体的标题,以及一个我将保留原样的描述。当我遇到这种情况时,我发现自己陷入困境:

<div class ="Content">
  <Strong>Title:</strong>
  description
</div>

如您所见,字符串实际上已经格式化,但我似乎找不到将标签和文本放在一起的方法。 我的脚本看起来像:

article = "" #this is where I normally store all the formatted text, it's necessary that I get all the formatted text as one loooong string before I Output
temp1=""
temp2""
result = soup.findAll("div", {"class": "Content"})
if(result!=none):
  x=0
  for(i in result.find("strong")):
    if(x==0):
      temp1 = "<strong>" + i.text + "</strong>"
      article += temp1
      x=1
    else:
      temp2 = i.nextSibling #I know this is wrong
      article += temp2
      x = 0
print(article) 

它实际上会抛出一个 AttributeError 但它是错误的,因为输出是“当你打算调用 find() 时你调用了 find_all() 吗?”。

我也知道我不能像那样使用 .nextSibling,而且我正在为一些看起来很容易解决的问题而失去它...

我需要得到的是:“标题:描述”

提前感谢您的回复。

编辑

到select<strong>使用:

soup.select_one('div.Content strong')

然后到 select 它的 nextSibling:

strong.nextSibling

你我需要 strip 它来去除空格,....:[=​​18=]

strong.nextSibling.strip()

以防万一

您可以使用 ANSI 转义序列打印某些内容 bold,...但我不确定您为什么要这样做。这是你的问题应该改进的地方。

例子

from bs4 import BeautifulSoup

html='''
<div class ="Content">
  <Strong>Title:</strong>
  description
</div>
'''
soup = BeautifulSoup(html,'html.parser')
text = soup.find('div', {'class': 'Content'}).get_text(strip=True).split(':')

print('3[1m'+text[0]+': 3[0m'+ text[1])

输出

标题:描述

如果我不能很好地解释我想要完成的事情,我很抱歉,但这有点清晰;我实际上需要数据来生成对 CKEditor session 的 POST 请求,以便它将文本添加到 html 页面,但我需要先以某种方式格式化文本上传它。在这种情况下,我需要获取标签内的元素并以某种方式对其进行格式化,然后对描述执行相同的操作并将它们一个接一个地打印出来,例如请求可能如下所示:

http://server/upload.php?desc=<ul>%0D%0A%09<li><strong>Title%26nbsp%3B<%2strong>description<%2li><%2ul>

所以结果是:

  • 标题 1:描述

所以我需要做的是使用标签本身作为参考来区分标签内的元素和标签外的元素

您可能需要为此使用 html。示例:

text="""<div class ="Content">
   <Strong>Title:</strong>
   description
</div>"""

import htql
ret = htql.query(text, "<div>{ col1=<strong>:tx; col2=<strong>:xx &trim }")
# ret=[('Title:', 'description')]