如何在BeautifulSoup中提取包含普通文本以及其他HTML标签的<span>内容?

时间:2019-03-10 11:49:51

标签: python html web-scraping beautifulsoup

使用BeautifulSoup,我试图提取<span>标签之间的内容。我使用string属性来获取所需的输出。如果<span>标签仅包含文本,则效果很好。但是,如果标签中放置了除普通文本之外的其他HTML标签,则失败。例如。

如果我刮了以下内容:

<span>Elegant, Furnished, Planned</span>

使用代码段:

soup.select_one('span').string

它工作正常,我得到的输出为:

Elegant, Furnished, Planned

但是,当我抓取以下内容时,我得到了None

<span>Elegant, <b>Furnished</b>, Planned</span>

帮我弄清楚。

2 个答案:

答案 0 :(得分:1)

应该工作正常。尝试使用lxml

from bs4 import BeautifulSoup as bs
html = '''
<span>Elegant, Furnished, Planned</span>
'''
soup = bs(html, 'lxml')
soup.select_one('span').text

答案 1 :(得分:0)

我认为您可以尝试以下一种方法:

url = 'your.example.net'
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page, "html.parser")

for span in soup.find_all('span'):
    print (span.text)