Отображение длинного названия валюты в таблице с MySQL - 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):
        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 = response.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()
    rate = scrapy.Field()
    currencyl = 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,
                    rate text,
                    currencyl 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()

1 Ответ

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

В вашем currencyl -выборе есть две небольшие ошибки:
Сначала вам нужно перебрать exchange_rate вместо response (как вы уже правильно сделали для валюты и курса).
Кроме того, есть . отсутствует в вашем xpath().

Так что это должно работать как положено:

currencyl = exchange_rate.xpath('.//td[@class="alignLeft"]//text()').extract_first()
...