注意: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())
还不快抢沙发