Показать более одной строки элементов в SQL - PullRequest
0 голосов
/ 03 мая 2020

Я делаю веб-скребок, используя Scrapy, который собирает данные об обменных курсах, и хочу отобразить данные в таблице, используя mysql, но с моим кодом он отображает только первый набор данных для валюты и обменный курс, и я не уверен, как заставить его отображать все данные. Вот мой код:

Код паука:

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):

        items = EurotocurrencyItem()

        currency = response.xpath('//td[@class="currency"]//text()').extract()
        rate = response.css('.rate::text').extract()

        items['currency'] = currency
        items['rate'] = rate
        yield items

Код Piplines.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='notactualpassword',
            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,
                    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  )""", (
            item['currency'][0],
            item['rate'][0],
        ))
        self.conn.commit()

1 Ответ

2 голосов
/ 03 мая 2020

В логи c, которые вы используете в данный момент, у вас есть только 1 элемент, который выглядит примерно так:

item = {'currency': ["USD", "JPY", ...],
        'rate': ["1.0876", "115.87", ...]}

В вашем методе store_db вы будете вставлять только первый элемент каждого список в mysql. Вам следует переписать логи c в разборе, чтобы получить 1 элемент по обменному курсу:

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()
    rate = exchange_rate.css('.rate::text').extract_first()
    item['currency'] = currency
    item['rate'] = rate
    yield item

Если вы затем обновите свой метод store_db следующим образом, то будет хорошо до go:

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