【问题标题】:Python Regex to extract relative href linksPython正则表达式提取相对href链接
【发布时间】:2014-03-22 08:44:29
【问题描述】:

我有一个包含大量相关 href 链接的 html 文件,例如;

href="data/self/dated/station1_140208.txt">Saturday, February 08, 2014/a>br/>

文件中有大量其他 http 和 ftp 链接,
我需要一个输出 txt 文件;

14/02/08: station1_140208.txt  
14/02/09: station1_140209.txt  
14/02/10: station1_140210.txt  
14/02/11: station1_140211.txt  
14/02/12: station1_140212.txt  

我尝试自己编写,但我需要很长时间才能习惯 Python 正则表达式。
我可以打开源文件,应用一个我还不知道的特定正则表达式,然后将它写回磁盘。

我需要你在正则表达式方面的帮助。

【问题讨论】:

  • 使用 DOM 提取所有链接并检查相关链接。

标签: python regex hyperlink relative-path


【解决方案1】:
pattern = 'href="data/self/dated/([^"]*)"[^>]*>([\s\S]*?)</a>'

测试:

import re
s = """
<a href="data/self/dated/station1_140208.txt">Saturday, February 08, 2014</a>
br/>
<a href="data/self/dated/station1_1402010.txt">Saturday, February 10, 2014</a>
br/>
<a href="data/self/dated/station1_1402012.txt">Saturday, February 12, 2014</a>
br/>
"""
pattern = 'href="data/self/dated/([^"]*)"[^>]*>([\s\S]*?)</a>'
re.findall(pattern,s)

输出:

[('station1_140208.txt', 'Saturday, February 08, 2014'), ('station1_1402010.txt', 'Saturday, February 10, 2014'), ('station1_1402012.txt', 'Saturday, February 12, 2014')]

【讨论】:

  • 非常感谢 Kowalski,它完全符合我的要求。
【解决方案2】:

我知道这并不完全符合您的要求,但我想我会展示一种将链接文本中的日期转换为您在所需输出示例中显示的格式的方法 (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 文档。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    相关资源
    最近更新 更多