我知道这并不完全符合您的要求,但我想我会展示一种将链接文本中的日期转换为您在所需输出示例中显示的格式的方法 (dd/mm/yy)。我用BeautifulSoup从html中读取元素。
from bs4 import BeautifulSoup
import datetime as dt
import re
html = '<a href="data/self/dated/station1_140208.txt">Saturday, February 08, 2014</a><br/>'
p = re.compile(r'.*/station1_\d+\.txt')
soup = BeautifulSoup(html)
a_tags = soup.find_all('a', {"href": p})
>>> print a_tags # would be a list of all a tags in the html with relevant href attribute
[<a href="data/self/dated/station1_140208.txt">Saturday, February 08, 2014</a>]
names = [str(a.get('href')).split('/')[-1] for a in a_tags] #str because they will be in unicode
dates = [dt.datetime.strptime(str(a.text), '%A, %B %m, %Y') for a in a_tags]
姓名和日期使用list comprehensions
strptime 从日期字符串中创建日期时间对象
>>> print names # would be a list of all file names from hrefs
['station1_140208.txt']
>>> print dates # would be a list of all dates as datetime objects
[datetime.datetime(2014, 8, 1, 0, 0)]
toFileData = ["{0}: {1}".format(dt.datetime.strftime(d, '%w/%m/%y'), n) for d in dates for n in names]
strftime 将日期重新格式化为示例中的格式:
>>> print toFileData
['5/08/14: station1_140208.txt']
然后将toFileData 中的条目写入文件
有关我在上面的代码中使用的方法(例如soup.find_all() 和a.get())的信息,我建议您通过顶部的链接查看BeautifulSoup 文档。希望这会有所帮助。