第一步我们要导入 scrapy框架 ,还是使用 cmd 的 pip 指令
pip install scrapy
然后让我检测一下是否已经导入完成,这里是在 cmd 命令中输入
C:\Users\zhaihao\BaiduStocks>scrapy -h
如果已经导入会出现 scrapy 的相关信息
这里我开始的时候出现了错误:
timeouterror: [winerror 10060] 由于连接方在一段时间后没有正确答复或 连接的主机没 site:blog.youkuaiyun.com
这个错误的话,把防火墙关掉就ok了
首先我们要新建一个项目
C:\Users\zhaihao>scrapy startproject BaiduStocks
然后生成一个名为 stocks 的爬虫
C:\Users\zhaihao>cd BaiduStocks
C:\Users\zhaihao\BaiduStocks>scrapy genspider stocks baidu.com
配置stocks.py 文件
# -*- coding: utf-8 -*-
import scrapy
import re
class StocksSpider(scrapy.Spider):
name = "stocks"
start_urls = ['https://quote.eastmoney.com/stocklist.html']
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.scrapy.org/en/latest/topics/item-pipeline.html
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
因为这里我们新建了一个类 BaidustocksInfoPipeline ,这里为了让scrapy 框架掌握这个类,就需要配置 settings.py,要把一下部分修改,就是把原来的类修改成 BaidustocksInfoPipeline 类
# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
#ITEM_PIPELINES = {
# 'BaiduStocks.pipelines.BaidustocksInfoPipeline': 300,
#}
最后我们可以查看该爬虫的相关信息
C:\Users\zhaihao\BaiduStocks>scrapy crawl stocks