我想用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 不会单独对结束标记进行操作 - 它们被视为同一元素的一部分。
如果你想把 <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>
分开,因为它们是同一事物的一部分。
关于python - 使用 BeautifulSoup 在 HTML 中搜索和替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2073541/