【问题标题】:Combine find_all beautiful soup tags into one string将 find_all 漂亮的汤标签组合成一个字符串
【发布时间】:2018-11-02 08:05:00
【问题描述】:

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

我怎样才能抛弃标签并将它们组合成一个字符串,以便它输出为“公司名称有限公司”?

原始 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>

【问题讨论】:

  • 你可以使用 element.get_text() 方法来获取元素的值而不是完整的元素。

标签: python html web-scraping beautifulsoup


【解决方案1】:

尝试以下方法:-

outputString = ' '.join([item.get_text() for item in company_string])

它将返回一个字符串,其中包含用空格连接的所有元素的值。

【讨论】:

    【解决方案2】:

    使用.text

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

    【讨论】:

    • 完美!只是工作。谢谢阿卡什
    猜你喜欢
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 2015-05-03
    • 1970-01-01
    • 2014-12-19
    相关资源
    最近更新 更多