当前位置: 首页 > 面试题库 >

使用BeautifulSoup在HTML中搜索和替换

管和志
2023-03-14
问题内容

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

编辑

我认为这将类似于:

soup.findAll('a').

在文档中,有一个:

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

因此,我认为这将遵循以下原则:

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

但这不起作用,并且python help()不能提供太多帮助


问题答案:

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

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不会单独对end标签进行操作-它们被视为同一元素的一部分。

如果要按照注释中的要求将<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>因为它们是同一事物的一部分。



 类似资料: