这是我的python代码,用于从https://bpbd.jatengprov.go.id/category/laporan-bencana/中抓取新闻数据
# -*- 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专家都能帮助我
发布于 2019-02-20 13:59:43
在谷歌搜索和阅读问答之后,我找到了插入列表的方法(正如我之前所说的那样,是多个数组)。
基本上,我遵循youtube上的scrapy教程,而不是以这种方式将数据查询到mysql中。在我能够抓取数据之后,我需要插入数据
首先我们必须知道我们的数据类型是什么,所以我发现我的数据类型是list而不是array。这是我在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))希望它能帮上忙
https://stackoverflow.com/questions/54629498
复制相似问题