从已解析的Beautiful Soup列表中删除<br>标签?

mam*_*eri 14 python beautifulsoup html-parsing

我正在进入一个包含我想要的所有行的for循环:

page = urllib2.urlopen(pageurl)
soup = BeautifulSoup(page)
tables = soup.find("td", "bodyTd")
for row in tables.findAll('tr'):
Run Code Online (Sandbox Code Playgroud)

在这一点上,我有我的信息,但是

<br />
Run Code Online (Sandbox Code Playgroud)

标签毁了我的输出.

删除这些最简洁的方法是什么?

Mu *_*ind 19

如果你想将<br />'s 转换为换行符,请执行以下操作:

def text_with_newlines(elem):
    text = ''
    for e in elem.recursiveChildGenerator():
        if isinstance(e, basestring):
            text += e.strip()
        elif e.name == 'br':
            text += '\n'
    return text
Run Code Online (Sandbox Code Playgroud)


Kab*_*bie 16

for e in soup.findAll('br'):
    e.extract()
Run Code Online (Sandbox Code Playgroud)

  • 这有效,但它提取br之间的任何文本,所以它不会只删除额外的br,你将无法将文本与br分开,因为它将删除它 (3认同)
  • 就我而言,该解决方案也摆脱了br标签周围的文字,因此我使用`e.replace_with('')`将br标签替换为空格。 (2认同)