Scrapy爬虫支持多种HTML信息提取方法
- BeautifulSoup
- lxml
- re
- XPath Selector
CSS Selector
对于spider来讲,有很多种信息处理方法,下面介绍CSS Selector的基本使用。CSS Selector的基本使用
股票数据Scrapy爬虫需要如下三个步骤:
- 步骤一:建立工程和Spider模板
- 步骤二:编写Spider (要符合具体的功能和使用)
- 步骤三:编写ITEM Pipelines (对后期提取的数据做相关处理)
步骤一:建立工程和Spider模板
建立工程和Spider模板
步骤二:编写Spider
- 配置stocks.py文件
- 修改对返回页面的处理
- 修改对新增URL爬取请求的处理
# -*- coding: utf-8 -*-
# stocks.py
import scrapy
import re
class StocksSpider(scrapy.Spider):
name = "stocks"
# 初始链接是东方财富网股票列表网址
start_urls = ['http://quote.eastmoney.com/stocklist.html']
# 从爬回的网页中找到个股的代码,并且生成与百度股票相关的URL
def parse(self, response):
# for循环对页面a标签的href进行提取
for href in response.css('a::attr(href)').extract():
try:
# 获取股票代码
stock = re.findall(r"[s][hz]\d{6}", href)[0]
# 生成百度股票URL
url = 'http://gupiao.baidu.com/stock/' + stock + '.html'
# 将url作为新的请求重新提交给scrapy框架,
# callback给出了处理这个url响应的处理函数,命名为parse_stock
yield scrapy.Request(url, callback=self.parse_stock)
except:
continue
def parse_stock(self, response):
# 这个函数要返回个股页面信息给item pipeline,是字典类型
infoDict = {}
# 找到stock-bets区域
stockInfo = response.css('.stock-bets')
# 在这个区域中找到bets-name,提取出字符串
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
修改settings.py文件
ITEM_PIPELINES = {
'BaiduStocks.pipelines.BaidustocksInfoPipeline': 300,
}