首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将多个Scrapy数据插入mysql

问将多个Scrapy数据插入mysql
EN

Stack Overflow用户
提问于 2019-02-11 19:23:27
回答 1查看 159关注 0票数 1

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

代码语言:javascript
复制
# -*- 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中?

代码语言:javascript
复制
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(),
    }

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

代码语言:javascript
复制
        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专家都能帮助我

EN

回答 1

Stack Overflow用户

发布于 2019-02-20 13:59:43

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

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

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

代码语言:javascript
复制
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)

则查询如下

代码语言:javascript
复制
mycursor.execute("INSERT INTO berita (judul, isi, tag) VALUES (%s, %s, %s)", (item1, item2, items3))

希望它能帮上忙

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54629498

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档