Home > Mobile >  How can I add a comma or separator when scrapping results using BeautifulSoup?
How can I add a comma or separator when scrapping results using BeautifulSoup?

Time:12-24

I'm trying to generate my scrapping result based on the following syntaks:

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

The result is:

<ol >
    <li><span >Author 1</span></li>
    <li><span >Author 2</span></li>
    <li><span >Author 3</span></li>
</ol>

When I add .text, the results I have is:

Author 1Author 2Author 3

How can I convert it to:

Author 1, Author 2, Author 3

CodePudding user response:

To add a comma as the separator, instead of calling .text use the .get_text() method with passing a comma , to the separator argument:

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

Output:

Author 1, Author 2, Author 3
  • Related