【问题标题】:What is wrong with my web scraper code (python3.4)我的网络爬虫代码有什么问题(python3.4)
【发布时间】:2015-04-04 17:55:08
【问题描述】:

我正在尝试从网站上抓取表格。它运行但我没有得到我的文件的输出。我哪里错了?

代码:

from bs4 import BeautifulSoup

import urllib.request

f = open('nbapro.txt','w')
errorFile = open('nbaerror.txt','w')

page = urllib.request.urlopen('http://www.numberfire.com/nba/fantasy/full-fantasy-basketball-projections')

content = page.read()
soup =  BeautifulSoup(content)

tableStats = soup.find('table', {'class': 'data-table xsmall'})
for row in tableStats.findAll('tr')[2:]:
 col = row.findAll('td')

 try: 
    name = col[0].a.string.strip()
    f.write(name+'\n')
 except Exception as e:
    errorFile.write (str(e) + '******'+ str(col) + '\n')
    pass

f.close
errorFile.close

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup html-parsing


    【解决方案1】:

    问题是您尝试抓取的表格数据是通过在浏览器端调用 javascript 代码来填写的。 urllib 不是浏览器,因此无法执行 javascript。

    如果你想通过urllibBeautifulSoup解决它,你必须从script标签中提取JSON对象并通过json.loads()加载它。例如,打印玩家姓名:

    import json
    import re
    import urllib.request
    from bs4 import BeautifulSoup
    
    
    soup = BeautifulSoup(urllib.request.urlopen('http://www.numberfire.com/nba/fantasy/full-fantasy-basketball-projections'))
    
    script = soup.find('script', text=lambda x: x and 'NF_DATA' in x).text
    data = re.search(r'NF_DATA = (.*?);', script).group(1)
    data = json.loads(data)
    
    for player_id, player in data['players'].items():
        print(player['name'] + ' ' + player['last_name'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      相关资源
      最近更新 更多