使用Python 2.7x从href标记中提取字符串

时间:2015-06-30 21:19:28

标签: python regex python-2.7 beautifulsoup

我目前正在使用Beautifulsoup4从HTML页面中提取“a href”标签。我正在使用Beautifulsoup4中的find_all查询,它正常工作并返回我正在寻找的'a href'标签。返回的示例如下:

"<a href="manage/foldercontent.html?folder=Pictures" style="background-image: url(shares/Pictures/DefaultPicture.png)" target="content_window" title="Vaya al recurso compartido Pictures">Pictures</a>"

我现在要做的只是提取"<a href="manage/foldercontent.html?folder=Pictures"而不是上面返回的完整内容。

我的代码如下:

req = urllib2.Request(example_url)
response = urllib2.urlopen(req)
soup = BeautifulSoup(response.read(), from_encoding=response.info().getparam('charset'))
for link in soup.find_all('a', href=True):
    # The below 'if' is to filter out only relevant 'a href' tags
    if "foldercontent.html?folder" in link['href']: 
        print link

这可以修改我搜索的内容,还是必须在返回的字符串中运行正则表达式?

1 个答案:

答案 0 :(得分:4)

您可以使用CSS selectors

for link in soup.select('a[href*="foldercontent.html?folder"]'):

[<attribute>*="<substring>"]语法匹配包含子字符串的任何属性值。

请注意,您返回的是Element个对象,而不是字符串;如果您需要从匹配的URL中解析出特定信息,您可以使用urlparse library解析link['href']值以获取URL路径,或仅查询查询字符串,或将查询字符串解析为其组成部分。