BeautifulSoup修改text值

python 2022-05-07

注意:target.text能获取text的值,但是无法修改text值,要用target.string修改

from bs4 import BeautifulSoup
import os

with open("index.html","r",encoding="utf-8") as htmlfile:
    html=htmlfile.read()
    soup = BeautifulSoup(html, 'lxml')  #生成BeautifulSoup对象
    targets = soup.find_all('a') #所有名称为a的节点
    for target in targets:
        #此地不能用target.text
        target.string="中卫日报("+target["href"][27:37]+")"
        htfile=os.path.join(os.getcwd(),target["href"])
        print(htfile)
        #if os.path.exists(htfile):
        #    target["style"]="color:red;"
        #else:
        #    target["style"]="color:green;"

with open("index.html","w") as fp:
    fp.write(soup.prettify())
知识共享署名声明
本文由 herokay 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论