【问题标题】:How to visualise data from Scrapy scraped data如何从 Scrapy 抓取的数据中可视化数据
【发布时间】:2020-05-03 08:14:10
【问题描述】:

我用 Scrapy 做了一个网络爬虫,它从https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html 收集汇率数据,并通过 My SQL 在表格中显示数据(货币缩写名称、货币全名和汇率)。我想要做的是,每次与上次抓取相比,汇率上升或下降时,都会在货币中添加一列,说明它增加或减少了多少百分比。我该怎么做?这是我到目前为止的代码:

currency_scraper.py:

import scrapy
from ..items import EurotocurrencyItem

class CurrencySpider(scrapy.Spider):
    name = 'currency'
    start_urls = [
        'https://www.ecb.europa.eu/stats/policy_and_exchange_rates/euro_reference_exchange_rates/html/index.en.html'
    ]

    def parse(self, response):
        exchange_rates = response.xpath('//*[@class="forextable"]//tr')
        for exchange_rate in exchange_rates:
            item = EurotocurrencyItem()
            currency = exchange_rate.xpath('.//td[@class="currency"]//text()').extract_first()
            currencyl = exchange_rate.xpath('.//td[@class="alignLeft"]//text()').extract_first()
            rate = exchange_rate.css('.rate::text').extract_first()

            item['currency'] = currency
            item['currencyl'] = currencyl
            item['rate'] = rate

            yield item

items.py:

import scrapy


class EurotocurrencyItem(scrapy.Item):
    currency = scrapy.Field()
    currencyl = scrapy.Field()
    rate = scrapy.Field()

pipelines.py:

import mysql.connector


class EurotocurrencyPipeline:

    def __init__(self):
        self.create_connection()
        self.create_table()

    def create_connection(self):
        self.conn = mysql.connector.connect(
            host='localhost',
            user='root',
            passwd='notrealpassword',
            database='currency'
        )
        self.curr = self.conn.cursor()

    def create_table(self):
        self.curr.execute("""DROP TABLE IF EXISTS currency_tb""")
        self.curr.execute("""create table currency_tb(
                    currency text,
                    currencyl text,
                    rate text
                    )""")

    def process_item(self, item, spider):
        self.store_db(item)
        return item

    def store_db(self, item):
        self.curr.execute("""insert into currency_tb values(%s, %s, %s  )""", (
            item['currency'],
            item['currencyl'],
            item['rate']
        ))
        self.conn.commit()

【问题讨论】:

    标签: python mysql scrapy


    【解决方案1】:

    几种可能性:

    • 在process_item 方法(将对每个项目执行)中,您可以对mysql 运行查询以取回货币之前的汇率。然后,您可以将其与商品中的价格进行比较,然后插入
    • 您在管道中添加了一个方法 open_spider,您可以在其中查询字典中每种货币的所有当前汇率。然后,在 process_item 中,您将字典中的货币汇率与当前项目中的汇率进行比较。这样你只需要在数据库中做 1 次选择
    • 您更改了数据库结构,因此每次抓取时总是插入一个值。然后可以在抓取逻辑之外完成计算减少/增加的逻辑。

    【讨论】:

      猜你喜欢
      • 2019-02-13
      • 2015-02-05
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2013-10-02
      • 2017-09-04
      相关资源
      最近更新 更多