beautifulsoup如何删除所有img的某个属性

初学py,百度了很多,就只找到这段,只能处理第一个找到的img。
处理所有img找不到。
感觉是应该用find_all,但是find_all返回的是数组,单独处理他不会改变整体html

from bs4 import BeautifulSoup
#包含很多img的一大段html
html='...'
soup=BeautifulSoup(html,"html.parser")
del soup.img["alt"]
del soup.img["width"]
print(soup)
阅读 3.8k
1 个回答

找了这么久,才在官方完整找到遍历代码
推荐第一种,边遍历边修改,好像效率高些
方法一

soup = BeautifulSoup(content,"html.parser")

for child in soup.descendants:
    if(child.name=='img'):
        child['data-src']="@@@@@@@@@@@@@@@@@@@@@@@@@2"
        print(child)

方法二

soup = BeautifulSoup(content,"html.parser")

tags = soup.find_all("img",attrs={"class":"aa cc"})
for  a_tag in tags:
    a_tag.decompose()
print(soup)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题