【问题标题】:How to extract the text between some anchor tags?如何提取一些锚标签之间的文本?
【发布时间】:2012-11-06 08:52:55
【问题描述】:

我需要从 HTML 页面中提取艺术家的姓名。这是页面的sn-p:

 </td>
 <td class="playbuttonCell">
   <a class="playbutton preview-track" href="/music/example" data-analytics-redirect="false"  >
      <img class="transparent_png play_icon" width="13" height="13" alt="Play" src="http://cdn.last.fm/flatness/preview/play_indicator.png" style="" />
    </a>
  </td>
  <td class="subjectCell" title="example, played 3 times">
    <div>
      <a href="/music/example-artist"   >Example artist name</a>

我已经尝试过了,但没有完成这项工作。

import urllib
from bs4 import BeautifulSoup

html = urllib.urlopen('http://www.last.fm/user/Jehl/charts?rangetype=overall&subtype=artists').read()
soup = BeautifulSoup(html)
print soup('a')

for link in soup('a'):
    print html

我在哪里搞砸了?

【问题讨论】:

  • 您在循环中打印 html 而不是 link
  • 哦,是的,我打印了 html 以在此处发布代码并忘记更改。但仍然不是我需要的解决方案,它会打印整个锚标签。
  • 我已经在这里回答了你的问题,它有效stackoverflow.com/questions/13233548/…
  • 也许str(link)link.prettify() 是你想要的?
  • 这不是你最初问 muchacho 的问题。您的问题应该更具描述性,我们无法读懂您的想法。

标签: python anchor beautifulsoup scraper


【解决方案1】:
spans = soup.find_all("div", {"class": "overlay tran3s"})
    for span in spans:
        links = span.find_all('a')
        for link in links:
            print(link.text)

【讨论】:

  • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
【解决方案2】:

你可以试试这个:

In [1]: from bs4 import BeautifulSoup

In [2]: s = # Your string here...

In [3]: soup = BeautifulSoup(s)

In [4]: for anchor in soup.find_all('a'):
   ...:     print anchor.text
   ...:
   ...:

here lies the text i need

这里,find_all 方法返回一个包含所有匹配锚标签的列表,之后我们可以打印text 属性来获取标签之间的值。

【讨论】:

  • find_all 方法名不是更像 Pythonic 吗?而且它并不完全返回一个迭代器,而是一个列表。
  • @CristianCiupitu 是的,我脑子里还有旧的 BeautifulSoup 方法。至于迭代器评论,我责怪我已经过了睡觉时间:)
  • @muchacho 不要复制和粘贴In [1]:...:。这些是来自他的 ipython 终端的行号。它不是有效的python。
  • 可以从一个 .txt 文件中打开多个 url 并一次抓取网页内容吗?
  • @muchacho 是的,您可以将它包装在一个循环访问 URL 的 for 循环中,也许将匹配项存储在一个新列表中。我建议阅读for 循环和open - 这应该让你开始:)
【解决方案3】:
for link in soup.select('td.subjectCell a'):
    print link.text

selects (just like CSS) a 元素内的 td 元素具有 subjectCell 类。

【讨论】:

    【解决方案4】:

    soup.findAlllink.attrs 可用于轻松读取href 属性。

    工作代码:

    soup = BeautifulSoup(html)
    
    for link in soup.findAll('a'):
        print (link.attrs['href'])
    

    输出:

    /music/example
    /music/example-artist
    

    【讨论】:

      【解决方案5】:

      正则表达式是你的朋友。作为 RocketDonkey 正确使用 BeautifulSoup 的答案的替代方案;您可以使用像

      这样的正则表达式解析 soup('a')
      >([a-zA-Z]*|[0-9]|(\w\s*)*)</a>
      

      您可以利用re.findall 方法直接抓取锚标记之间的文本。

      【讨论】:

      • 用正则表达式解析 html 就像穿着骑士的盔甲跳舞。
      猜你喜欢
      • 2016-05-10
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多