scrapy框架开发中pipelines模块将数据写入mysql数据库中

目标:构建一个爬虫项目,获取新浪新闻网站中多个新闻网页中的标题和关键词等信息,将数据写入到数据库。

代码:

  1. 创建一个scrapy项目testdb 命令: scrapy startproject testdb
  1. 修改items.py文件
python 复制代码
import scrapy


class TestdbItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    name = scrapy.Field()
    keyword = scrapy.Field()
  1. 创建数据库和表:

create table mytb(

title CHAR(20) NOT NULL,

keyword CHAR(255)

)engine=innodb default charset=utf8;

  1. 修改pipeline文件:
python 复制代码
import pymysql

class TestdbPipeline:
    def __init__(self):
        self.con=pymysql.connect(host='localhost',user='root',passwd='root',db='test',charset='utf8')
        self.cursor = self.con.cursor()


    def process_item(self, item, spider):
        name = item['name'][0]
        keyword = item['keyword'][0]
        print(name,keyword)
        sql="insert into mytb(title,keyword) values('"+name+"','"+keyword+"')"
        self.cursor.execute(sql)
        self.con.commit()
        return item
    def close_spider(self,spider):
        self.cursor.close()
  1. 修改settings文件:
python 复制代码
ITEM_PIPELINES = {
   "testdb.pipelines.TestdbPipeline": 300,
}
  1. 创建爬虫文件:sinanews.py

命令:scrapy genspider -t basic sinanews sina.com.cn

python 复制代码
import scrapy
from testdb.items import TestdbItem

class TestSinaNews(scrapy.Spider):
    name = 'sinanews'
    allowed_domains = ['sina.com.cn']
    start_urls = ('https://news.sina.com.cn/',)

    def parse(self, response):
        item = TestdbItem()
        item['name'] = response.xpath("/html/head/title/text()").extract()
        item['keyword'] = response.xpath("/html/head/meta[@name='keywords']/@content").extract()
        yield item

运行:命令:scrapy crawl sinanews --nolog

相关推荐
傻啦嘿哟6 天前
天气数据爬虫:基于Scrapy爬取全国天气,做可视化大屏
c++·爬虫·scrapy
小白学大数据8 天前
拼多多反爬对抗实战:Scrapy 中间件化采集架构解析
开发语言·scrapy·中间件·架构
毕业设计7039 天前
(免费领源码)django空气净化器销售系统09218- java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
python·scrapy·mysql·pycharm·django·flask·pandas
v:PLLucky2016 天前
农作物病虫害检测识别系统
深度学习·scrapy·算法·百度·微信公众平台
TomEval20 天前
【测AI】第05篇:Python 爬虫进阶 —— 动态页面爬取与 Scrapy 框架
人工智能·爬虫·python·scrapy·自动化
Data_Journal1 个月前
使用 AutoScraper 进行网页抓取:分步教程
大数据·开发语言·数据库·python·scrapy
Data_Journal1 个月前
如何将网页抓取用于机器学习
大数据·开发语言·数据库·python·scrapy
圆脸脸lxj1 个月前
scrapy框架开发中pipelines模块将数据写入记事本中
scrapy
深蓝电商API1 个月前
Scrapy 架构源码解析
爬虫·scrapy