【问题标题】:How can I add a comma or separator when scrapping results using BeautifulSoup?使用 BeautifulSoup 报废结果时如何添加逗号或分隔符?
【发布时间】:2022-01-24 19:55:35
【问题描述】:

我正在尝试根据以下语法生成我的报废结果:

authors = item.find('ol', 'Authors')

结果是:

<ol class="Authors">
    <li><span class="author">Author 1</span></li>
    <li><span class="author">Author 2</span></li>
    <li><span class="author">Author 3</span></li>
</ol>

当我添加.text时,我得到的结果是:

Author 1Author 2Author 3

如何将其转换为:

Author 1, Author 2, Author 3

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    要添加逗号作为分隔符,而不是调用 .text,请使用 .get_text() 方法并将逗号 , 传递给 separator 参数:

    print(
        ''.join(
            tag.get_text(strip=True, separator=", ")
            for tag in soup.find_all("ol", class_="Authors")
        )
    )
    

    输出:

    Author 1, Author 2, Author 3
    

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2020-07-01
      • 2017-09-13
      • 2021-07-29
      • 1970-01-01
      • 2022-11-22
      • 1970-01-01
      • 2016-03-08
      • 1970-01-01
      相关资源
      最近更新 更多