【问题标题】:Python and Scrapy, and attempting to get scraped data into MariaDB/MYSQL DatabasePython 和 Scrapy,并试图将抓取的数据放入 MariaDB/MYSQL 数据库
【发布时间】:2020-10-27 16:39:30
【问题描述】:

我知道下面的代码还没有完成,但我只是想做的就是将这些收益结果输入我的 MARIADB。我花了太多时间梳理 Stackoverflow,寻找这个答案。该代码运行良好,我可以手动添加最终项目以将内容输入带有静态信息的数据库,但我已经尝试了 for 循环中的所有内容。

我只需要最后几行代码来解决这个问题,我相信我可以继续最终抓取数据。

import scrapy
import mysql.connector
from scrapy.selector import Selector

mydb = mysql.connector.connect(
  host="localhost",
  database="database",  
  user="root",
  password="password"
)

mycursor = mydb.cursor()
sql = "INSERT INTO testTable (name) VALUES (%s)"

class scrapysclass(scrapy.Spider):
    name = "scrapy-name"

    start_urls = ['url']

    def parse(self, response):
        quotes = str(response.xpath('//comment()').extract())
        quotes = quotes.replace('<!--','').replace('-->','')
        sel = Selector(text=quotes)
        for row in sel.xpath('//table[@id="tableid"]//tbody/tr'):
            yield {
                'first' : row.xpath('td[1]//text()').extract_first(),
                'last': row.xpath('td[2]//text()').extract_first(),
                'handle' : row.xpath('td[3]//text()').extract_first(),
            }`

【问题讨论】:

    标签: python mysql scrapy mariadb mariasql


    【解决方案1】:

    由于您正在与蜘蛛旁边的数据库建立连接,您可以让光标执行插入查询而不是产生项目。

    sql = "INSERT INTO testTable (name, last_name, handle) VALUES (%s, %s, %s)"
    
    ...
    
    for row in sel.xpath('//table[@id="tableid"]//tbody/tr'):
        first = row.xpath('td[1]//text()').extract_first()
        last = row.xpath('td[2]//text()').extract_first()
        handle = row.xpath('td[3]//text()').extract_first()
        
        data = (first, last, handle)
        mycursor.execute(sql, data)
    

    请注意,我已经更改了您的 sql 语句,因为我不清楚哪些数据应该放在那里。

    我必须指出,这不是最好的解决方案。

    理想情况下,您的蜘蛛应该只负责抓取数据,并且您应该编写一个项目管道来将数据插入数据库。

    当你编写一个管道时,每次蜘蛛产生一个它被抓取的项目时,process_item 方法将被调用来处理那个项目。 Here in the docs 你会发现一些管道的例子。

    【讨论】:

    • 这与我自己想出的答案基本相同,但这也有效。
    猜你喜欢
    • 2017-02-08
    • 2017-09-04
    • 2017-08-07
    • 2011-10-17
    • 2013-05-23
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多