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

Extracting string from a href tag with Python 2.7x

我目前正在使用 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

修改我搜索的内容是否可行,或者我是否必须 运行 在返回的字符串中使用正则表达式?

您可以使用 CSS selectors:

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

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

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