【问题标题】:Sifting a list returned from a webscrape produced with Beautiful Soup筛选从使用 Beautiful Soup 制作的网络爬虫返回的列表
【发布时间】:2012-06-26 14:20:05
【问题描述】:

我正在使用 python 来编码。我一直在尝试抓取 nba 选秀前景的名称、球队图片和学院。但是,当我抓取学院的名称时,我会同时获得学院页面和学院名称。我怎样才能让我只看到大学?我尝试将 .string 和 .text 添加到锚(anchor.string)的末尾。

import urllib2
from BeautifulSoup import BeautifulSoup
# or if your're using BeautifulSoup4:
# from bs4 import BeautifulSoup

list = []
soup = BeautifulSoup(urllib2.urlopen(
                            'http://www.cbssports.com/nba/draft/mock-draft'
                             ).read()
                     )

rows = soup.findAll("table",
                    attrs = {'class':'data borderTop'})[0].tbody.findAll("tr")[2:]

for row in rows:
  fields = row.findAll("td")
  if len(fields) >= 3:
    anchor = row.findAll("td")[2].findAll("a")[1:]
    if anchor:
      print anchor

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    不仅仅是:

    print anchor
    

    使用:

    print anchor[0].text
    

    【讨论】:

      【解决方案2】:

      html 中锚点的格式是 <a href='web_address'>Text-that-is-displayed</a>,所以除非已经有一个花哨的 html 解析器库(我敢打赌有,只是不知道),否则您可能需要使用某种正则表达式来解析出你想要的锚部分。

      【讨论】:

      • BeautifulSoup 就是那个“花哨的 html 解析器库”。而且您无法使用正则表达式解析 HTML。见stackoverflow.com/a/1732454/10077
      • 谢谢,我得研究一下 BeautifulSoup。至于正则表达式,我喜欢阅读那篇文章,但第二个答案(以及赢得赏金的那个)确实说您可以解析有限的已知 html 子集,我认为这是由 findAll 返回的.
      猜你喜欢
      • 2016-05-24
      • 2013-04-17
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多