Skip to main content
 首页 » 编程设计

python之将 find_all 漂亮的汤标签组合成一个字符串

2025年05月04日25TianFang

我正在使用 beautifulsoup 和 html 解析器执行抓取,并选择了我想要使用的 html 部分并将其保存为“容器”。

from urllib.request import urlopen as uReq 
from bs4 import BeautifulSoup as soup 
import ssl 
 
my_url = 'https://www._________.co.uk/' 
context = ssl._create_unverified_context() 
uClient = uReq(my_url, context=context) 
page_html = uClient.read() 
uClient.close() 
 
page_soup = soup(page_html, "html.parser") 
containers = page_soup.findAll("div",{"class":"row"}) 

当涉及到在一个范围内彼此相邻的几个标签时,我遇到了挑战。

我可以通过使用来调出结果

company_string = container.span.find_all("b") 

返回以下内容:

[<b>Company</b>, <b>Name</b>, <b>Limited</b>] 

我怎样才能抛弃标签并将它们组合成一个字符串,以便它输出为“Company Name Limited”?

原文html在这里:

<span class="company"> 
<a href="/cmp/Company-Name-Limited" onmousedown="this.href =  
appendParamsOnce(this.href, 'xxxx')" rel="noopener" target="_blank"> 
<b>Company</b> <b>Name</b> <b>Limited</b> 
</a> 
</span> 

请您参考如下方法:

使用.text

>>> output = ' '.join([item.text for item in company_string]) 
'Company Name Limited'