我需要拉SRC和HREF子元素离开IMG和一个分别的标签,更改的内容,并有更改保存到原来的文件。我正在使用Python 3和Beautiful Soup。对于上下文,我需要能够在目录中的一系列文件上实现这一点,因此简单的查找和替换不会成功。这是我目前的代码:
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"))
我怎么能以实际节省的方式做到这一点?
发布于 2018-09-10 09:28:09
经过进一步的研究,我能够通过改变线条来修改我需要的子元素
a.get("href").replace_with(link)
img.get("src").replace_with(pic)
同
a['href'] = link
img['src'] = pic
https://stackoverflow.com/questions/-100008850
复制相似问题