从包含在 HTML 标记和不带标记的字符串中的一系列字符串中提取文本

考虑以下 HTML:


<li>

  <a href="url">

    <b>This</b>

    " is "

    <b>a</b>

    " test "

    <b>string</b>

    "!"

  </a>

</li>

我想提取<a>标签之间的所有文本,除了"!". 换句话说,包含在第一个开头<b>和最后一个结尾之间的文本</b>: This is a test string。


from bs4 import BeautifulSoup


html = '''

<li>

<a href="url">

<b>This</b>

" is "

<b>a</b>

" test "

<b>string</b>

"!"

</a>

</li>

'''

soup = BeautifulSoup(html)

anchor = soup.a

请注意,<b>没有标签的标签和字符串的数量会有所不同,next或者next_sibling不起作用。


有没有更简单的方法来做到这一点?


编辑: 理想情况下,我想要一种方法,即使我在最后一个</b>.


慕尼黑5688855
浏览 121回答 2
2回答

慕娘9325324

试试下面的代码result = ''.join([i.strip().replace('"', '') for i in anchor.strings if i.strip()][:-1])print(result)输出'This is a test string'

斯蒂芬大帝

根据您的问题和评论,我认为获取子字符串的索引并对 HTML 的整个子集进行操作可以满足您的需求。让我们首先创建一个函数来检索子字符串的所有索引(参见@AkiRoss 的回答):def findall(p, s):&nbsp; &nbsp; i = s.find(p)&nbsp; &nbsp; while i != -1:&nbsp; &nbsp; &nbsp; &nbsp; yield i&nbsp; &nbsp; &nbsp; &nbsp; i = s.find(p, i+1)然后使用它来查找<b>和的出现</b>。opening_b_occurrences = [i for i in findall('<b>', html)]# has the value of [21, 40, 58]closing_b_occurrences = [i for i in findall('</b>', html)]# has the value of [28, 44, 67]现在您可以使用该信息来获取 HTML 的子字符串来进行文本提取:first_br = opening_b_occurrences[0]last_br = closing_b_occurrences[-1] # getting the last one from listtext_inside_br = html[first_br:last_br]中的文本text_inside_br现在应该是'<b>This</b>\n" is "\n<b>a</b>\n" test "\n<b>string'. 您现在可以清理它,例如通过附加</br>回它并使用 BeautifulSoup 提取值或仅使用正则表达式来执行此操作。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python