【问题标题】:Extracting text between link tags using BeautifulSoup in Python在 Python 中使用 BeautifulSoup 提取链接标签之间的文本
【发布时间】:2015-05-29 23:47:34
【问题描述】:

我的 HTML 代码如下所示:

<a href="/Content.aspx?id=102966" id="mylink" target="_blank">EZSTORAGE - PACK IT. STORE IT. WIN - <img src="/images/usa.png" style="border:none; height:14px; margin-bottom:-2px;"/> Nationwide - <span title="college students/staff of schools in valid states">Restrictions</span> - Ends 6/30/15</a>

我正在尝试提取呈现此 HTML 时显示的文本。

更具体地说,对于这个示例“a”标签,我正在尝试提取“EZSTORAGE - 打包。存储它。WIN - Nationwide - Restrictions - Ends 6/30/15”

但我无法提取全文,因为它被“img”标签和“span”分解。

为了提供更多上下文,我一直在使用下面的代码来搜索所有“a”标签并提取链接文本。

for link in soup.find_all('a', id='mylink'):
    raw.append(link)
    link_text = link.contents[0].encode('utf-8')
    sweeps.append(link_text)

#output: 'EZSTORAGE - PACK IT. STORE IT. WIN - '

任何见解将不胜感激!

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    你不能像这个 MWE 那样使​​用link.text 而不是link.contents

    text = """
    <a href="/Content.aspx?id=102966" id="mylink" target="_blank">EZSTORAGE - PACK IT. STORE IT. WIN - <img src="/images/usa.png" style="border:none; height:14px; margin-bottom:-2px;"/> Nationwide - <span title="college students/staff of schools in valid states">Restrictions</span> - Ends 6/30/15</a>
    """
    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(text)
    
    for link in soup.find_all('a', id='mylink'):
        link_text = link.text
        print link_text
    

    结果:

    EZSTORAGE - PACK IT. STORE IT. WIN -  Nationwide - Restrictions - Ends 6/30/15
    

    【讨论】:

      【解决方案2】:

      您可以使用常规查找所有文本

      import urllib,urllib2,re
      
      content=r'<a href="/Content.aspx?id=102966" id="mylink" target="_blank">EZSTORAGE - PACK IT. STORE IT. WIN - <img src="/images/usa.png" style="border:none; height:14px; margin-bottom:-2px;"/> Nationwide - <span title="college students/staff of schools in valid states">Restrictions</span> - Ends 6/30/15</a>''
      
      
      
      links=re.findall(r'>(.*?)<',content)
      a=""
      for link in links:
          a=a+link
      print a
      

      return "EZSTORAGE - 打包。存储。获胜 - 全国范围 - 限制 - 2015 年 6 月 30 日结束"

      【讨论】:

        猜你喜欢
        • 2011-09-09
        • 2016-03-27
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        相关资源
        最近更新 更多