str.replace返回ValueError美丽的汤

时间:2020-05-21 13:51:46

标签: python html beautifulsoup

我有以下html:

<body><h3>Full Results for race 376338</h3>"Category","Position","Name","Time","Team"<br>"A","1","James","20:20:00","5743"<br><br>"A","2","Matt","20:15:00"<br>

它像<br> # some text <br>一样持续数百行。 我想在每个
处创建一个新行,因此它是CSV格式,如下所示:

<body><h3>Full Results for race 376338</h3>"Category","Position","Name","Time","Team"
<br>"A","1","James","20:20:00","5743"<br>
<br>"A","2","Matt","20:15:00"<br>

我有这个代码:

soup = BeautifulSoup(html_string, features="html.parser")

    for br in soup.find_all('br'):
        soup.replace_with("\n")

这样我得到错误:ValueError: Cannot replace one element with another when the element to be replaced is not part of a tree. 我需要更改什么?

1 个答案:

答案 0 :(得分:1)

您想要text属性。

In [15]: soup.text
Out[15]: 'Full Results for race 376338"Category","Position","Name","Time","Team"\n"A","1","James","20:20:00","5743"\n"A","2","Matt","20:15:00"'

In [16]: soup.text.split()
Out[16]: 
['Full',
 'Results',
 'for',
 'race',
 '376338"Category","Position","Name","Time","Team"',
 '"A","1","James","20:20:00","5743"',
 '"A","2","Matt","20:15:00"']

In [17]: soup.text.split()[4:]
Out[17]: 
['376338"Category","Position","Name","Time","Team"',
 '"A","1","James","20:20:00","5743"',
 '"A","2","Matt","20:15:00"']

或使用get_text方法。

In [24]: soup.get_text()
Out[24]: 'Full Results for race 376338"Category","Position","Name","Time","Team"\n"A","1","James","20:20:00","5743"\n"A","2","Matt","20:15:00"'

In [25]: [text for text in soup.stripped_strings]
Out[25]: 
['Full Results for race 376338',
 '"Category","Position","Name","Time","Team"',
 '"A","1","James","20:20:00","5743"',
 '"A","2","Matt","20:15:00"']

最后两点直接来自文档。