Python学习笔记_5初识Scrapy框架(实现抓取股票行情)

stock.py

# -*- coding: utf-8 -*-
import scrapy
from items import StockstarItem,StockstarItemloader
class StockSpider(scrapy.Spider):
    name = 'stock'#定义爬虫名称
    allowed_domains = ['quote.stockstar.com']#定义爬虫域
    start_urls = ['http://quote.stockstar.com/stock/ranklist_a_3_1_1.html']#定义开始爬虫链接
    def parse(self, response):#撰写爬虫逻辑
     page=int(response.url.split("_")[-1].split(".")[0])#抓取页码
     item_nodes = response.css('#datalist tr')
     for item_node in item_nodes:# 根据item文件中定义的字段内容,进行字段内容抓取
        item_loader = StockstarItemloader(item=StockstarItem(),selector=item_node)
        item_loader.add_css("code","td:nth-child(1) a::text")
        item_loader.add_css("abbr","td:nth-child(2) a::text")
        item_loader.add_css("last_trade","td:nth-child(3) span::text")
        item_loader.add_css("chg_ratio","td:nth-child(4) span::text")
        item_loader.add_css("chg_amt","td:nth-child(5) span::text")
        item_loader.add_css("chg_ratio_5min", "td:nth-child(6) span::text")
        item_loader.add_css("volume", "td:nth-child(7)::text")
        item_loader.add_css("turn_over", "td:nth-child(8)::text")
        stock_item = item_loader.load_item()#保存json信息
        yield stock_item
     if item_nodes:
                next_page=page+1
                next_url=response.url.replace("{0}.html".format(page), "{0}.html".format(next_page))
                yield scrapy.Request(url=next_url, callback=self.parse)
                pass

itmes.py

 
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy
from scrapy.loader import ItemLoader
from scrapy.loader.processors import TakeFirst
class StockstarItemloader(ItemLoader):
#自定义itemloader,用于存储爬虫所抓取的字段内容
 default_output_processor = TakeFirst()
class StockstarItem(scrapy.Item):#建立相应的字段
    # define the fields for your item here like:
    #name = scrapy.Field()
    code = scrapy.Field()#股票代码
    abbr = scrapy.Field()#股票简称
    last_trade = scrapy.Field()#最新价
    chg_ratio = scrapy.Field()#涨跌幅
    chg_amt = scrapy.Field()#涨跌额
    chg_ratio_5min = scrapy.Field()#5分钟涨幅
    volume = scrapy.Field()#成交量
    turn_over = scrapy.Field()#成交额
    pass

为解决在json文件中出现/Uxxx编码错误 采用在settings文件中附加

FEED_EXPORT_ENCODING = 'utf-8'代码解决
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
这里是一个简单的Python-Scrapy爬取百度搜索结果并对搜索结果进行分析的例子: 首先,我们需要安装Scrapy和lxml库。在命令行中输入以下命令: ``` pip install scrapy pip install lxml ``` 然后,我们可以创建一个名为baidu_spider的新项目,并在项目中创建一个名为baidu的新爬虫。在命令行中输入以下命令: ``` scrapy startproject baidu_spider cd baidu_spider scrapy genspider baidu www.baidu.com ``` 现在,我们在baidu_spider/spiders/baidu.py文件中编写我们的代码。我们将使用Scrapy的Selector来选择我们想要的数据。代码如下: ```python import scrapy class BaiduSpider(scrapy.Spider): name = "baidu" allowed_domains = ["www.baidu.com"] start_urls = ["http://www.baidu.com/s?wd=python"] def parse(self, response): # 获取搜索结果 results = response.xpath('//div[@class="result c-container "]') for result in results: # 获取标题和链接 title = result.xpath('.//h3/a/text()').extract_first().strip() link = result.xpath('.//h3/a/@href').extract_first() # 获取摘要 abstract = result.xpath('.//div[@class="c-abstract"]//text()').extract() abstract = "".join(abstract).strip() # 打印结果 print(title) print(link) print(abstract) ``` 在这个例子中,我们首先定义了我们的爬虫的名称,允许的域名和起始URL。然后我们定义了一个parse函数来处理响应。在parse函数中,我们使用XPath选择器来选择搜索结果。我们使用extract_first()和extract()方法来提取标题、链接和摘要。最后,我们打印了结果。 现在,我们可以在baidu_spider目录中运行以下命令来运行我们的爬虫: ``` scrapy crawl baidu ``` 这将启动我们的爬虫并开始爬取百度搜索结果。在控制台中,您应该能够看到我们的爬虫正在输出搜索结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zpf_37

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值