gpt4 book ai didi

python - Beautifulsoup 获取标签内容的最简单方法

转载 作者:行者123 更新时间:2023-11-28 03:13:06 27 4
gpt4 key购买 nike

问题是 contents Beautifulsoup 标签的是列表而不是字符串。因此,我必须使用 for 循环来获取标签内的内容。这很麻烦。有更好的方法吗?

from bs4 import BeautifulSoup
html_doc = u'<li><span class="def">1. <span class="cat">cat</span>example<span class="ex">ex</span></span></li>'
soup = BeautifulSoup(html_doc)
div = soup.find("span", class_='def')
print div.contents
result = ''
for divcont in div.contents:
result = result + unicode(divcont)
print result

输出:

[u'1. ', <span class="cat">cat</span>, u'example', <span class="ex">ex</span>]
1. <span class="cat">cat</span>example<span class="ex">ex</span>

字符串 1. <span class="cat">cat</span>example<span class="ex">ex</span>是我想要的,但我需要一种更简单的方法来获得它。

最佳答案

使用join :

from bs4 import BeautifulSoup
html_doc = u'<li><span class="def">1. <span class="cat">cat</span>example<span class="ex">ex</span></span></li>'
soup = BeautifulSoup(html_doc)
div = soup.find("span", class_='def')
print(''.join(str(e) for e in div))

关于python - Beautifulsoup 获取标签内容的最简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29687391/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com