【问题标题】:how to retrieve text from anchor href attribute in python如何从python中的锚href属性中检索文本
【发布时间】:2016-11-03 00:31:34
【问题描述】:

假设我有一个这样的链接:

link = '<a href="some text">...</a>'

有什么方法可以从锚点 href 属性中检索文本,所以结果将是这样的:

hrefText = 'some text'

提前谢谢你

【问题讨论】:

    标签: python href


    【解决方案1】:

    这是一种方式:

    import re
    print re.search('(?<=<a href=")[^"]+',link).group(0)
    

    或者,

    print re.search(r'<a\s+href="([^"]+)',link).group(1)
    

    【讨论】:

      【解决方案2】:

      虽然您可以拆分或使用正则表达式,但对于更模块化强大的工具集,您可以使用

      美汤:https://www.crummy.com/software/BeautifulSoup/

      示例代码:

      from bs4 import BeautifulSoup 
      link = '<a href="some text">...</a>'
      soup = BeautifulSoup(link, "html.parser")
      for anchor in soup.find_all('a', href=True):
          print anchor['href']
      

      或者,对于单个函数,您可以这样做:

      from bs4 import BeautifulSoup 
      
      def getHref( link ):
          soup = BeautifulSoup(link, "html.parser")
          return soup.find_all('a', href=True)[0]['href']
      

      【讨论】:

      • 仅仅解析一个href链接是不是有点矫枉过正?
      • 虽然这是一个较小的问题,但很多人在未来阅读这篇文章可能会尝试做更多的抓取:)
      【解决方案3】:

      您可以使用 bs4 并为此请求 lib。

      import requests
      from bs4 import BeautifulSoup
      url = 'https://examplesite.com/'
      source = requests.get(url)
      text = source.text
      soup = BeautifulSoup(text, "html.parser")
      for link in soup.findAll('a', {}):
         href = '' + link.get('href')
         title = link.string
         print("hrefText = ", href)
      

      希望这会有所帮助:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-18
        • 1970-01-01
        • 2012-10-13
        • 1970-01-01
        • 1970-01-01
        • 2015-05-09
        • 2018-10-11
        • 1970-01-01
        相关资源
        最近更新 更多