Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 删除<;a>;通过HREF属性从字符串中添加标记_Python - Fatal编程技术网

Python 删除<;a>;通过HREF属性从字符串中添加标记

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

我有一个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 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)