标题:股票数据Scrapy爬虫未成功
只看楼主
康明贤
Rank: 2
来 自:NWPU
等 级:论坛游民
帖 子:46
专家分:32
注 册:2017-10-23
结帖率:75%
已结贴  问题点数:20 回复次数:2 
股票数据Scrapy爬虫未成功
错误:
 File "D:\papachong\BaiduStocks\BaiduStocks\spiders\stocks.py", line 22, in parse_stock
    name = stockInfo.css('.bets-name').extract()[0]
IndexError: list index out of range
该程序来自北理的嵩天老师网络爬虫课。
搜索更多相关主题的帖子: 爬虫 out list 票数 成功 
2019-10-11 19:38
wp231957
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
来 自:神界
等 级:版主
威 望:422
帖 子:13681
专家分:53296
注 册:2012-10-18
得分:20 
回复 楼主 康明贤
不发代码只发错误信息,我也是服了
信息看不懂吗,大致意思是说爬的结果是空

DO IT YOURSELF !
2019-10-12 07:38
康明贤
Rank: 2
来 自:NWPU
等 级:论坛游民
帖 子:46
专家分:32
注 册:2017-10-23
得分:0 
回复 2楼 wp231957
stocks.py
程序代码:
# -*- coding: utf-8 -*-
import scrapy
import re

 

 
class StocksSpider(scrapy.Spider):
    name = "stocks"
    start_urls = ['https://quote.']

 
    def parse(self, response):
        for href in response.css('a::attr(href)').extract():
            try:
                stock = re.findall(r"[s][hz]\d{6}", href)[0]
                url = 'https://gupiao.baidu.com/stock/' + stock + '.html'
                yield scrapy.Request(url, callback=self.parse_stock)
            except:
                continue

 
    def parse_stock(self, response):
        infoDict = {}
        stockInfo = response.css('.stock-bets')
        name = stockInfo.css('.bets-name').extract()[0]
        keyList = stockInfo.css('dt').extract()
        valueList = stockInfo.css('dd').extract()
        for i in range(len(keyList)):
            key = re.findall(r'>.*</dt>', keyList[i])[0][1:-5]
            try:
                val = re.findall(r'\d+\.?.*</dd>', valueList[i])[0][0:-5]
            except:
                val = '--'
            infoDict[key]=val

 
        infoDict.update(
            {'股票名称': re.findall('\s.*\(',name)[0].split()[0] + \
             re.findall('\>.*\<', name)[0][1:-1]})
        yield infoDict




pipelines.py:
程序代码:
# -*- coding: utf-8 -*-
 
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.
 

 
class BaidustocksPipeline(object):
    def process_item(self, item, spider):
        return item

 
class BaidustocksInfoPipeline(object):
    def open_spider(self, spider):
        self.f = open('BaiduStockInfo.txt', 'w')

 
    def close_spider(self, spider):
        self.f.close()

 
    def process_item(self, item, spider):
        try:
            line = str(dict(item)) + '\n'
            self.f.write(line)
        except:
            pass
        return item

下面是settings.py文件中被修改的区域:
程序代码:
# Configure item pipelines
# See https://scrapy.
ITEM_PIPELINES = {
    'BaiduStocks.pipelines.BaidustocksInfoPipeline': 300,
}

千里之行,始于足下。
2019-10-13 22:16



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-497198-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.216725 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved