Python 删除<;a>;通过HREF属性从字符串中添加标记
我有一个HTML正文,一个可能的摘录:Python 删除<;a>;通过HREF属性从字符串中添加标记,python,Python,我有一个HTML正文,一个可能的摘录: body = 'Hi what <a href="url_example_1" other-attribute>is</a> your <a href="url_example2" other-attribute>name</a>?....other stuffs' 有没有正则表达式或其他方法可以让这个新主体删除url\u以删除?…其他内容 试试这个: from bs4 import BeautifulSo
body = 'Hi what <a href="url_example_1" other-attribute>is</a> your <a href="url_example2" other-attribute>name</a>?....other stuffs'
有没有正则表达式或其他方法可以让这个新主体删除url\u以删除?…其他内容
试试这个:
from bs4 import BeautifulSoup
body = 'HTML code here'
to_delete = 'depricated url'
soup = BeautifulSoup(body)
elements = soup.find_all("a")
for element in elements:
if element['href'] == to_delete:
element.replace_with("%s" % element.text)
body = soup
print(body)
它可以被构建(regex),但是应该根据什么逻辑来实现呢?(仅删除第一次出现的内容等)html正文是否始终是有效的html?@andreis11我有一个body
列表和一个url\u to\u remove
相关列表(每个正文一个url)。该url在中仅出现一次body@L3viathan我不能确定,如果你的a标签真的总是这么简单,而且从不包含任何其他属性,它会删除整个标签,我想把文本放在里面,看看我的例子
new_body = 'Hi what is your <a href="url_example2" other-attribute>name</a>?....other stuffs'
from bs4 import BeautifulSoup
body = 'HTML code here'
to_delete = 'depricated url'
soup = BeautifulSoup(body)
elements = soup.find_all("a")
for element in elements:
if element['href'] == to_delete:
element.replace_with("%s" % element.text)
body = soup
print(body)