python - 向mysql中插入多条Scrapy数据

标签 python mysql insert scrapy

这是我从 https://bpbd.jatengprov.go.id/category/laporan-bencana/ 抓取新闻数据的 python 代码'

# -*- coding: utf-8 -*-
import scrapy
class BepeSpider(scrapy.Spider):
name = 'bepe'
allowed_domains = ['bpbd.jatengprov.go.id']
start_urls = ['https://bpbd.jatengprov.go.id/category/laporan-bencana/']
COUNT_MAX = 100
count = 0

def parse(self, response):
    for quote in response.css('div.post'):
        item = {
            'judul': quote.css('h2.post-title > a::text').extract_first(), 
            'teks': quote.css('div.entrytext > p::text').extract_first(), 
            'tag': quote.css('div.up-bottom-border > p.postmetadata > a::text').extract(),
        }
        yield item
        self.count = self.count + 1
        #following pagination link
        next_page_url = response.css('div.alignright > a::attr(href)').extract_first() #dapatkan link untuk selanjutnya

    if (self.count < self.COUNT_MAX):
        next_page_url = response.urljoin(next_page_url)
        yield scrapy.Request(url=next_page_url, callback=self.parse)

有什么办法可以用这样的数组将我的爬行数据插入到mysql中吗?

item = {
        'judul': quote.css('h2.post-title > a::text').extract_first(), 
        'teks': quote.css('div.entrytext > p::text').extract_first(), 
        'tag': quote.css('div.up-bottom-border > p.postmetadata > a::text').extract(),
    }

我试过下面的代码,但它无法插入任何数据

        conn = Connection()
        mycursor = conn.cursor()
        sql = "insert into berita(judul, isi, tag) values(%s, %s, %s)"

        item = {
            'judul': quote.css('h2.post-title > a::text').extract_first(), 
            'teks': quote.css('div.entrytext > p::text').extract_first(), 
            'tag': quote.css('div.up-bottom-border > p.postmetadata > a::text').extract(),
        }
        val=(item['judul'], item['teks'], item['tag'])
        mycursor.execute(sql,val)
        conn.commit()

抱歉我的英语不好,我希望 python 专家可以帮助我

最佳答案

经过谷歌搜索和阅读问答后,我找到了插入列表的方法(如我之前所说的多个数组)。

基本上,我遵循 youtube 上的 scrapy 教程,而类(class)不是通过这种方式将数据查询到 mysql 中的。在我能够抓取数据后,我需要插入数据

首先我们必须知道我们的数据类型是什么,所以我发现我的数据类型是列表而不是数组。然后这是我在youtube scrapy教程中找不到的代码

item1 = quote.css('h2.post-title > a::text').extract_first()
item2 = quote.css('div.entrytext > p::text').extract_first()        
item3 = quote.css('div.up-bottom-border > p.postmetadata > a::text').extract()
items3 = ', '.join(item3)

下面是查询

mycursor.execute("INSERT INTO berita (judul, isi, tag) VALUES (%s, %s, %s)", (item1, item2, items3))

希望对你有帮助

关于python - 向mysql中插入多条Scrapy数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54629498/

相关文章:

mysql - 从 MySQL 到 MS SQL Server 的 SQL 查询错误

php - 缓慢的 MySQL 性能和 sleep 查询

php - 如何有效地插入完全相同的行保存一个变化的列?

c++ - 如何(有效地)插入以 map 为值的 map ?

python - 如何在Python函数中应用嵌套的while循环

python - 使用 python 套接字发送/接收数据

python - 如何在 Mac OS X 上的 Python 交互式 shell 中输入英镑字符 (£)?

javascript - Laravel5 : Many to many relationship

python - BigQuery python 插入记录 (\w client.insert_rows)

python - 沙盒/逐行运行 python 代码