【问题标题】:Trying to extract text from specific tag that contains other tags. BeautifulSoup尝试从包含其他标签的特定标签中提取文本。美丽汤
【发布时间】:2022-02-02 02:47:49
【问题描述】:

我有以下html

    <div class="1" style="">
         text0
         <span class="2">text1</span>
      <div class="3" title="something" name="something1">
         text2
         <span class="small">text3</span>
      </div>
    </div>

我正在尝试使用 BeautifulSoup 提取 text0。

但是

div = soup.find_all("div", {"class":"1", "style":"").text.strip()

div = soup.find("div", {"class":"1", "style":"").get_text()

不工作。有什么想法吗????

【问题讨论】:

    标签: python html python-3.x beautifulsoup tags


    【解决方案1】:

    会发生什么?

    首先,您的代码中存在拼写错误,缺少结束 },因此您的所有选择都会出现错误。

    find_all() 不起作用,因为您无法直接从 result set 获取文本,您必须对其进行迭代。

    要获取一个元素的所有文本,您的行应更改为:

     soup.find("div", {"class":"1", "style":""}).text.strip()
    

    如何只获取text0?

    您可以使用stripped_strings并从结果集中选择第一个元素:

    list(soup.find("div", {"class":"1", "style":""}).stripped_strings)[0]
    

    您可以迭代 contents 并在出现下一个标签时中断:

    for e in soup.find("div", {"class":"1", "style":""}).contents:
        if not e.name:
            print(e.text.strip())
            break
    

    【讨论】:

      猜你喜欢
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 2019-11-07
      相关资源
      最近更新 更多