【问题标题】:Extracting string from a href tag with Python 2.7x使用 Python 2.7x 从 href 标签中提取字符串
【发布时间】:2015-09-17 20:46:08
【问题描述】:

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

我现在要做的只是提取"&lt;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

这是否可以通过修改我搜索的内容来实现,或者我是否必须在返回的字符串中运行正则表达式?

【问题讨论】:

    标签: python regex python-2.7 beautifulsoup


    【解决方案1】:

    你可以使用CSS selectors:

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

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

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

    【讨论】:

      猜你喜欢
      • 2014-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多