【问题标题】:Extract text between link tags in python using BeautifulSoup使用 BeautifulSoup 在 python 中的链接标签之间提取文本
【发布时间】:2011-09-09 05:28:55
【问题描述】:

我有一个这样的html代码:

<h2 class="title"><a href="http://www.gurletins.com">My HomePage</a></h2>

<h2 class="title"><a href="http://www.gurletins.com/sections">Sections</a></h2>

我需要提取“a”标签之间的文本(链接描述)。我需要一个数组来存储这些:

a[0] = "我的主页"

a[1] = "节"

我需要使用 BeautifulSoup 在 python 中执行此操作。

请帮帮我,谢谢!

【问题讨论】:

    标签: python text tags extract beautifulsoup


    【解决方案1】:

    你可以这样做:

    import BeautifulSoup
    
    html = """
    <html><head></head>
    <body>
    <h2 class='title'><a href='http://www.gurletins.com'>My HomePage</a></h2>
    <h2 class='title'><a href='http://www.gurletins.com/sections'>Sections</a></h2>
    </body>
    </html>
    """
    
    soup = BeautifulSoup.BeautifulSoup(html)
    
    print [elm.a.text for elm in soup.findAll('h2', {'class': 'title'})]
    # Output: [u'My HomePage', u'Sections']
    

    【讨论】:

    • @Mehmet Helvici:你能更具体地说明什么不起作用吗?你有没有得到一些错误或..,我发布的上面的代码对我来说是正确的。
    【解决方案2】:

    print [a.findAll(text=True) for a in soup.findAll('a')]

    【讨论】:

      【解决方案3】:

      以下代码提取“a”标签之间的文本(链接描述)并存储在一个数组中。

      >>> from bs4 import BeautifulSoup
      >>> data = """<h2 class="title"><a href="http://www.gurletins.com">My 
      HomePage</a></h2>
      ...
      ... <h2 class="title"><a href="http://www.gurletins.com/sections">Sections</a>
      </h2>"""
      >>> soup = BeautifulSoup(data, "html.parser")
      >>> reqTxt = soup.find_all("h2", {"class":"title"})
      >>> a = []
      >>> for i in reqTxt:
      ...     a.append(i.get_text())
      ...
      >>> a
      ['My HomePage', 'Sections']
      >>> a[0]
      'My HomePage'
      >>> a[1]
      'Sections'
      

      【讨论】:

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