从经过解析的美丽汤列表中移除<br>标记?

2024-04-28 19:53:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

<br />

标签正在破坏我的输出。

最干净的方法是什么?


Tags: infortablespagefindurllib2trurlopen
3条回答

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

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
for e in soup.findAll('br'):
    e.extract()

用空格替换开头的标记 Beautiful soup还接受urlopen对象上的.read(),因此这应该可以工作--

page = urllib2.urlopen(pageurl)
page_text=page.read()
new_text=re.sub('</br>',' ',page_text)
soup = BeautifulSoup(new_text)
tables = soup.find("td", "bodyTd")
for row in tables.findAll('tr'):
.....

re.sub用空白替换了br标记

相关问题 更多 >