如何在python3中用Beautiful Soup修改子元素

2024-04-24 03:07:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要分别从imga标签中拉出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"))

我怎样才能真正节省开支呢?你知道吗


Tags: 文件srcimggetwithlinkopenfind
1条回答
网友
1楼 · 发布于 2024-04-24 03:07:25

经过进一步的研究,我能够通过改变行来修改所需的子元素

a.get("href").replace_with(link)
img.get("src").replace_with(pic)

a['href'] = link
img['src'] = pic

相关问题 更多 >