Removing new line '\n' from the output of python BeautifulSoup

前端 未结 3 1919
难免孤独
难免孤独 2021-01-12 01:52

I am using python Beautiful soup to get the contents of:

abc def
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 02:15

    Unless I'm missing something, just combine strip and list comprehension.

    Code:

    from bs4 import BeautifulSoup as bsoup
    
    ofile = open("test.html", "r")
    soup = bsoup(ofile)
    
    res = ",".join([a.get_text().strip() for a in soup.find("div", class_="path").find_all("a")])
    print res
    

    Result:

    abc,def,ghi
    [Finished in 0.2s]
    

提交回复
热议问题