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

标签 python html web-scraping beautifulsoup

我正在使用 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'

关于python - 将 find_all 漂亮的汤标签组合成一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50486567/

相关文章:

html - 如何在不使用选取框的情况下使用 CSS 从右到左创建移动背景?

html - 使用固定宽度的列在 CSS 网格中居中

python - 我怎样才能在 BeautifulSoup 中得到下一个 child

html - 如何获取任何 URL 或网页的 Google 缓存年龄?

python - 返回列表的所有 "positions"

python : why a method from super class not seen?

python - 为什么我不能将 char 附加到 Python 中的空列表?

python - virtualenv 使用不正确的 sys.path

html - 如何删除无序列表创建的缩进

python - 使用 python 抓取隐藏的 jquery 值