使用python正则表达式提取干净的url

2024-05-23 14:25:59 发布

您现在位置:Python中文网/ 问答频道 /正文

谢谢!我使用了@nu11p01n73R的答案,这个post,我得到了大部分的url,但是在开头和结尾仍然有一些额外的“噪音”。理想情况下,我希望它只打印URL-http://something.some-因此regex将删除URL开头的<a herf=",并删除其末尾的" data-metrics='{"action" : "Click Story 2"}'>。我试图修改表达式来获得这个结果,但是我遇到了麻烦,URL的开头和结尾都是一个“-我想这会把我的regex搞乱了。有什么建议吗?在

URL在.txt文件中嵌入如下:

<a href="http://www.npr.org/blogs/parallels/2014/11/11/363018388/how-the-islamic-state-wages-its-propaganda-war" data-metrics='{"action":"Click Story 1"}' >

我希望输出是:

^{pr2}$

我最近使用的代码是:

file  = open("/Users/shannonmcgregor/Desktop/npr.txt", 'r')
for line in file:
    if re.search('<a href=[^>]*(islamic|praying|marines|comets|dyslexics)', line):
        print line

但这会返回,例如:

<a href="http://www.npr.org/blogs/parallels/2014/11/11/363018388/how-the-islamic-state-wages-its-propaganda-war" data-metrics='{"action":"Click Story 1"}' >

Tags: txthttpurldatawww结尾lineaction
2条回答

您可以使用re.findall函数将内容提取为

file  = open("/Users/shannonmcgregor/Desktop/npr.txt", 'r')
for line in file:
    if re.search('<a href=[^>]*(islamic|praying|marines|comets|dyslexics)', line):
        print re.findall(r'(?<=")[^"]*(?=")', line)[0]

将产生输出为

^{pr2}$

Regex不是解析html文件的正确工具。因为你的意思,我发布了这个解决方案。在

>>> import re
>>> file  = open("/Users/shannonmcgregor/Desktop/npr.txt", 'r')
>>> for i in file:
        if re.search('<a href="[^>"]*(islamic|praying|marines|comets|dyslexics)', i):
            i = re.sub(r'^.*?<a href="([^"]*)".*', r'\1', i)
            print(i)

^{pr2}$

相关问题 更多 >