我需要分别从img和a标签中拉出src和href子元素,更改内容,并将更改保存到原始文件中。我用的是Python3和靓汤。对于context,我需要能够在一个目录中的一系列文件上实现这一点,因此简单的查找和替换不会奏效。以下是我目前掌握的代码:
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"))
我怎样才能真正节省开支呢?你知道吗
经过进一步的研究,我能够通过改变行来修改所需的子元素
与
相关问题 更多 >
编程相关推荐