Вставить данные (список) из scrapy в mysql базу - PullRequest
0 голосов
/ 20 июня 2020

Я пытаюсь вставить список URL-адресов, которые я скопировал с веб-сайта, в базу данных mysql и все время получаю сообщение об ошибке «Python 'list' не может быть преобразован в тип MySQL». Это список из 120 URL-адресов, поэтому каждый URL-адрес должен быть в одной строке. Мне нужно l oop по списку и вставлять каждый URL-адрес в базу данных, но я не знаю, как это сделать правильно.
Проблема с кодом item['link']

для auto.py

import scrapy
import mysql.connector
from mysql.connector import Error
from scrapy_splash import SplashRequest
from scrapy.loader import ItemLoader
from dealers.items import  DealersItem

        

class AutoSpider(scrapy.Spider):
    name = 'dealers'
    allowed_domains = ['www.marlboroughford.com']

    script = '''
    function main(splash)
        local scroll_delay = 2
        local is_down = splash:jsfunc("function() { return((window.innerHeight + window.scrollY) >= document.body.offsetHeight);}")
        local scroll_to = splash:jsfunc("window.scrollTo")
        local get_body_height = splash:jsfunc("function() {return document.body.scrollHeight;}")
        assert(splash:go(splash.args.url))

        while not is_down() do
            scroll_to(0, get_body_height())
            splash:wait(scroll_delay)
        end        
        return splash:html()
    end
    '''
    
    def start_requests(self):    
        yield SplashRequest(url="https://marlboroughford.com/inventory/", callback=self.parse, endpoint="execute", args={'lua_source': self.script})


 #>>>>>>>>>> HERE IS THE PROBLEM <<<<<<<<<

    def parse(self, response):    
        item = DealersItem()
        item['car_maker'] = "Ford"
        item['link'] = response.xpath('/html/body/div/main/div/div/div/div/div/div/div/div/div/div/meta[2]/@content').extract()
        yield item



Это код в конвейерах .py

import scrapy
import mysql.connector
from mysql.connector import Error
from scrapy_splash import SplashRequest
from dealers.items import  DealersItem


class DealersPipeline:
    def process_item(self, item, spider):
        try:
            connection = mysql.connector.connect(host='localhost',
                                                    database='database',
                                                    user='root',
                                                    password='12345')

            if connection.is_connected():
                    db_Info = connection.get_server_info()
                    print("Connected to MySQL Server version ", db_Info)
                    cursor = connection.cursor()
                    cursor.execute("select database();")
                    record = cursor.fetchone()
                    print("You're connected to database: ", record)
                    
                    #>>>>>>>>>> HERE IS THE PROBLEM <<<<<<<<<

                    sql = "INSERT INTO cars_scraped (car_maker, link) VALUES (%s, %s)" 
                    val = [item['car_maker'], item['link'])]
                    
                    for links in item['link']:   
                        cursor.executemany(sql, val)
                        connection.commit()
                        print(cursor.rowcount, "record was inserted.")
                 
                    
        except Error as e:
            print("Error while connecting to MySQL", e)
        finally:
            if (connection.is_connected()):
                cursor.close()
                connection.close()
                print("MySQL connection is closed")



Это ошибка

Error while connecting to MySQL Failed processing format-parameters; Python 'list' cannot be converted to a MySQL type



Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...