用BeautifulSoup在HTML中搜索和替换

2024-07-05 14:15:02 发布

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

我想使用BeautfulSoup搜索并用<\a><br>替换<\a>。我知道如何使用urllib2打开,然后解析以提取所有<a>标记。我要做的是搜索并用结束标记加上中断替换结束标记。任何帮助,非常感谢。

编辑

我想它应该类似于:

soup.findAll('a').

在文档中,有一个:

find(text="ahh").replaceWith('Hooray')

因此,我假设它将沿着以下路线:

soup.findAll(tag = '</a>').replaceWith(tag = '</a><br>')

但这不起作用,python help()也没有提供太多


Tags: text文档标记br编辑tagfindurllib2
3条回答

这将在每个<a>...</a>元素的末尾插入一个<br>标记:

from BeautifulSoup import BeautifulSoup, Tag

# ....

soup = BeautifulSoup(data)
for a in soup.findAll('a'):
    a.parent.insert(a.parent.index(a)+1, Tag(soup, 'br'))

不能使用soup.findAll(tag = '</a>'),因为BeautifulSoup不单独操作结束标记-它们被视为同一元素的一部分。


如果您想按照您在注释中的要求将<a>元素放入<p>元素中,可以使用以下命令:

for a in soup.findAll('a'):
    p = Tag(soup, 'p') #create a P element
    a.replaceWith(p)   #Put it where the A element is
    p.insert(0, a)     #put the A element inside the P (between <p> and </p>)

同样,您不会分别创建<p></p>,因为它们是同一事物的一部分。

假设您知道有一个元素包含“br”标记标记,一种用不同字符串移除和替换“br”标记的方法如下:

originalSoup = BeautifulSoup("your_html_file.html")
replaceString = ", " # replace each <br/> tag with ", "
# Ex. <p>Hello<br/>World</p> to <p>Hello, World</p>
cleanSoup = BeautifulSoup(str(originalSoup).replace("<br/>", replaceString))

不替换结束标记;在BeautifulSoup中,处理的是一个文档对象模型,就像在浏览器中一样,而不是一个充满HTML的字符串。因此,如果不同时替换开始标记,则无法“替换”结束标记。

您要做的是在<a>...</a>元素之后立即插入一个新的<br>元素。为此,您需要找出父元素中<a>元素的索引,并在该索引之后插入新元素。例如

soup= BeautifulSoup('<body>blah <a href="foo">blah</a> blah</body>')
for link in soup.findAll('a'):
    br= Tag(soup, 'br')
    index= link.parent.contents.index(link)
    link.parent.insert(index+1, br)
# soup now serialises to '<body>blah <a href="foo">blah</a><br /> blah</body>'

相关问题 更多 >