如何在Python 3中使用Beautiful Soup修改子元素
我需要分别从img和a标记中提取src和href子元素,更改内容,并将更改保存到原始文件中。我正在使用Python 3和漂亮的汤。对于上下文,我需要能够在一个目录中的一系列文件上实现这一点,因此简单的查找和替换不会起作用。以下是我目前掌握的代码:如何在Python 3中使用Beautiful Soup修改子元素,python,html,python-3.x,beautifulsoup,Python,Html,Python 3.x,Beautifulsoup,我需要分别从img和a标记中提取src和href子元素,更改内容,并将更改保存到原始文件中。我正在使用Python 3和漂亮的汤。对于上下文,我需要能够在一个目录中的一系列文件上实现这一点,因此简单的查找和替换不会起作用。以下是我目前掌握的代码: from bs4 import BeautifulSoup with open("file.html") as fp: soup = BeautifulSoup(fp, "lxml") atags = soup.find_all("a",
from bs4 import BeautifulSoup
with open("file.html") as fp:
soup = BeautifulSoup(fp, "lxml")
atags = soup.find_all("a", href=True)
imgtags = soup.find_all("img", src=True)
for a in atags:
link = a.get("href")
if link.find("http"):
link = link.split("/")[-1]
tmp = link.replace("%20", " ")
link = tmp
link = link.split("?")[0]
a.get("href").replace_with(link)
print(a)
for img in imgtags:
pic = img.get("src")
pic = pic.split("/")[-1]
tmp = pic.replace("%20", " ")
pic = tmp
pic = pic.split("?")[0]
img.get("src").replace_with(pic)
print(img)
with open("file.html", "wb") as f_output:
f_output.write(soup.prettify("utf-8"))
我如何才能以实际节省的方式做到这一点?经过进一步研究,我能够通过更改行来修改所需的子元素
a.get("href").replace_with(link)
img.get("src").replace_with(pic)
与
经过进一步的研究,我能够通过更改行来修改所需的子元素
a.get("href").replace_with(link)
img.get("src").replace_with(pic)
与