使用Python re查找包含x的URL。

2024-10-01 07:38:34 发布

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

使用python 2.7.3、urllib和re,我正在查找包含以下内容的URL:

href="/dirone/Dir_Two/dirthree/"

url可能位于的位置,例如:

href="/dirone/Dir_Two/dirthree/5678-random-stuff-here-letters-and-numbers"

我想回来:

"/dirone/Dir_Two/dirthree/5678-random-stuff-here-letters-and-numbers"

使用此工具:

http://www.jslab.dk/tools.regex.php

我生成的正则表达式是:

/^href\="\/dirone\/Dir_Two\/dirthree\/"$/im

因此,这个正则表达式是否可以按以下方式与python和re一起使用:

object_name = re.findall('/^href\="\/dirone\/Dir_Two\/dirthree\/"$/im',url)
for single_url in object_name:
    do something

Tags: andreurlhereobjectdirrandomhref
2条回答

你真的想放弃^锚;我怀疑href永远不会在一行的开头。你知道吗

您不需要/im部分,它们应该被re.标志常量替换。这里有Perl正则表达式语法,Python没有专门的/.../flags语法。你知道吗

因此,有太多的转义,没有实际的Python字符串。实际上你并没有包括5678-random-stuff-here-letters-and-numbers部分。你知道吗

改用这个:

object_name = re.findall(r'href="(/dirone/Dir_Two\/dirthree/[^"/]*)"', url, re.I)

我删除了多行标志,因为删除了^的字符串的开头不再匹配。我在路径周围添加了一个组((...)),以便findall()返回这些,而不是整个匹配。[^"/]*部分匹配任何字符,而不是用来捕获文件名部分而不是另一个目录名的引号或斜杠。你知道吗

简短演示:

>>> import re
>>> example = '<a href="/dirone/Dir_Two/dirthree/5678-random-stuff-here-letters-and-numbers">'
>>> re.findall(r'href="(/dirone/Dir_Two\/dirthree/[^"/]*)"', example, re.I)
['/dirone/Dir_Two/dirthree/5678-random-stuff-here-letters-and-numbers']

与Martijn的答案类似,但使用beautifulsoup的前提是您拥有HTML。你知道吗

data = '<a href="/dirone/Dir_Two/dirthree/5678-random-stuff-here-letters-and-numbers">Content</a>'

from bs4 import BeautifulSoup
import re

soup = BeautifulSoup(data)
print [el['href'] for el in soup('a', href=re.compile('^/dirone/Dir_Two/.*'))]

相关问题 更多 >