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

相关推荐
深蓝电商API2 天前
Scrapy 架构源码解析
爬虫·scrapy
IPdodo_5 天前
2026年爬虫代理 IP 选择指南:从可用率、延迟到成本验收
网络协议·tcp/ip·scrapy·http·https·beautifulsoup·httpx
q5673152312 天前
Curl 报 CONNECT tunnel failed, response 6xx:排查思路全解
数据库·网络协议·scrapy·http·中间件·http代理
Data_Journal13 天前
Playwright vs Selenium:哪个是最佳无头浏览器
开发语言·python·scrapy·microsoft·编辑器
Data_Journal14 天前
如何使用 Python 抓取 Google Flights:分步指南
大数据·开发语言·数据库·python·scrapy
Data_Journal15 天前
用于网页抓取的 Node-unblocker
大数据·开发语言·数据库·python·scrapy
Data_Journal18 天前
使用 Scrapy 和 Splash 抓取无限滚动内容
scrapy
Minner-Scrapy18 天前
Scrapy 2.17 源码解析:Scheduler 调度器与磁盘/内存双队列
java·爬虫·python·scrapy·网络爬虫·twisted
tang7778918 天前
Scrapy框架动态IP自动轮换集成配置教程
爬虫·tcp/ip·scrapy·架构·爬虫代理·动态ip