【发布时间】:2018-08-01 15:50:29
【问题描述】:
我们网站上有一个指向 zip 文件夹的链接。它的 HTML 文件中的行显示如下:
<p><a href="Data/WillCounty_AddressPoint.zip">Address Points</a> (updated weekly)</p>
zip 文件夹的名称很快将使用当前日期更改,如下所示:
WillCounty_AddressPoint_02212018.zip
如何更改 HTML 中的对应行?
使用this 回答我有一个脚本。它运行时没有错误,但不会更改 HTML 文件中的任何内容。
import bs4
from bs4 import BeautifulSoup
import re
import time
data = r'\\gisfile\GISstaff\Jared\data.html' #html file location
current_time = time.strftime("_%m%d%Y") #date
#load the file
with open(data) as inf:
txt = inf.read()
soup = bs4.BeautifulSoup(txt)
#create new link
new_link = soup.new_tag('link', href="Data/WillCounty_AddressPoint_%m%d%Y.zip")
#insert it into the document
soup.head.append(new_link)
#save the file again
with open (data, "w") as outf:
outf.write(str(soup))
【问题讨论】:
-
你想把什么日期放在那里?固定日期/代码运行的当前日期/其他? (你说它是“每周”更新的,但你也有
current_time = time.strftime("_%m%d%Y") #date)。 -
我想把当前日期放在上面。由于 zip 文件夹中的文件将每周更新相应的日期,因此 HTML 中的 zip 名称也必须更改。
-
但这意味着
time.strftime("_%m%d%Y")在一周的 7 天中有 6 天给您一个无效的文件名? -
@roganjosh 我不确定为什么会这样。它可以正常工作。每次运行时都会给出当前日期。
标签: python html hyperlink beautifulsoup