【问题标题】:How to extract href attribute in html source code如何在html源代码中提取href属性
【发布时间】:2019-09-22 23:59:29
【问题描述】:

这是我正在处理的 HTML 源代码:

<a href="/people/charles-adams" class="gridlist__link">

所以我想做的是提取 href 属性,在这种情况下是“/people/charles-adams”,带有beautifulsoup 模块。我需要这个,因为我想用 soup.findAll 方法获取该特定网页的 html 源代码。但我正在努力从网页中提取此类属性。谁能帮我解决这个问题?

附: 我正在使用这种方法通过 Python 模块 beautifulSoup 获取 html 源代码:

request = requests.get(link, headers=header)
html = request.text
soup = BeautifulSoup(html, 'html.parser')

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    尝试类似:

    refs = soup.find_all('a')
    for i in refs:
        if i.has_attr('href'):
            print(i['href'])
    

    它应该输出:

    /people/charles-adams
    

    【讨论】:

      【解决方案2】:

      您可以告诉beautifulsoup 查找所有带有soup.find_all('a') 的锚标记。然后你可以用列表理解过滤它并获取链接。

      request = requests.get(link, headers=header)
      html = request.text
      soup = BeautifulSoup(html, 'html.parser')
      
      tags = soup.find_all('a')
      tags = [tag for tag in tags if tag.has_attr('href')]
      links = [tag['href'] for tag in tags]
      

      links 将是 ['/people/charles-adams']

      【讨论】:

      • @Vladimir 这会起作用,但我认为当分散在多行时会发生什么更清楚。
      猜你喜欢
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多