python+scrapy+mysql爬取故事网站
来源:互联网 发布:网络教育和函授 编辑:程序博客网 时间:2024/05/16 19:53
继续下文之前请确认你已经掌握了python、SQL、scrapy相关知识
环境准备
- centos7 (笔者习惯了centos7,其它系统也可)
- python3.6 (若用其他版本请注意版本区别)
- pymysql (用于连接数据库)
- scrapy
- mariaDB(centos7预装mariadb,实现方式和mysql差不多)
数据库准备
CREATE TABLE `story` ( `id` int AUTO_INCREMENT NOT NULL, `title` VARCHAR(225), `content` text, `type` varchar(60), PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;
创建scrapy爬虫项目
scrapy startproject story
- settings.py 末尾添加以下数据库配置
MYSQL_HOST = 'localhost'MYSQL_DBNAME = 'test' # 数据库名称MYSQL_USER = 'root' # 用户名MYSQL_PWD = 'root' # 密码
- 在spiders目录下新建
story_spider.py
# !/usr/bin/env python# -*- coding: utf-8 -*-import scrapyfrom story.items import StoryItem class StorySpider(scrapy.Spider): name = 'story_spider' allowed_domins = ['www.xigushi.com'] start_urls = [ 'http://www.xigushi.com/ymgs/', 'http://www.xigushi.com/thgs/', 'http://www.xigushi.com/aqgs/', 'http://www.xigushi.com/jcgs/', 'http://www.xigushi.com/lzgs/', 'http://www.xigushi.com/zlgs/', 'http://www.xigushi.com/xygs/', 'http://www.xigushi.com/rsgs/', 'http://www.xigushi.com/yygs/', 'http://www.xigushi.com/mrgs/', 'http://www.xigushi.com/qqgs/', 'http://www.xigushi.com/yqgs/', ] def parse(self, response): article_links = response.xpath('//div[@class="list"]//dd//li//@href').extract() for link in article_links: yield response.follow(link, callback=self.parse_article) next_page = response.xpath('//div[@class="list"]//div[@class="pages"]//li[@class="thisclass"]//following-sibling::li[@class="sy2"][1]//@href').extract_first() if next_page != None: yield response.follow(next_page, callback=self.parse) def parse_article(self, response): item = StoryItem() item['title'] = response.xpath('//div[@class="by"]//h1[1]//text()').extract_first().strip() item['type'] = response.xpath('//div[@class="by"]//dt[1]//a[2]/text()').extract_first().strip() item['content'] = '' for content in response.xpath('//div[@class="by"]//p/text()').extract(): item['content'] += content.strip() yield item
- 接下来修改pipelines.py实现数据插入数据库
# -*- coding: utf-8 -*-# Define your item pipelines here## Don't forget to add your pipeline to the ITEM_PIPELINES setting# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.htmlimport pymysqlimport pymysql.cursorsclass StoryPipeline(object): def __init__(self, conn): self._conn = conn @classmethod def from_settings(cls, settings): conn = pymysql.connect( host=settings['MYSQL_HOST'], user=settings['MYSQL_USER'], password=settings['MYSQL_PWD'], db=settings['MYSQL_DBNAME'], charset='utf8') return cls(conn) def process_item(self, item, spider): sql_search = 'select id from story where title="%s"' % item['title'] sql = 'insert into story(title, content, type) ' 'values("%s", "%s", "%s")' % (item['title'], item['content'], item['type']) try: with self._conn.cursor() as cursor: cursor.execute(sql_search) result_search = cursor.fetchone() # 查重,若数据库中不存在则插入 if result_search is None or result_search[0].strip() == '': cursor.execute(sql) self._conn.commit() except Exception as e: print("exception >>> ") print(e) self._conn.rollback() return item def close_spider(self, spider): this._conn.close()
- 再修改settings.py
ITEM_PIPELINES = { 'story.pipelines.StoryPipeline': 300,}
一切准备就绪开始爬取吧!
scrapy crawl story_spider
后记
本文采用的是xpath的方式获取内容,你也可以尝试其他风格哦,比如说css
阅读全文
0 0
- python+scrapy+mysql爬取故事网站
- python scrapy之爬取 zhengfu网站
- 用Python 的 Scrapy 爬取 网站
- scrapy爬取电影网站
- Python+scrapy+mysql实现爬取磁力链接
- scrapy(一)爬取动态网站
- scrapy框架爬取校花网站
- scrapy+xpath爬取不可描述网站
- 使用Scrapy爬取顶点小说整个网站的小说,入库Mysql!
- python scrapy爬取动态页面
- Python Scrapy 学习----自动爬取网页
- python-scrapy-爬取图片笔记
- Python使用Scrapy爬取妹子图
- Python+Scrapy 爬取豆瓣电影排行榜Top250
- python + Scrapy 爬取动态网页
- python scrapy框架爬取CNKI数据
- python,scrapy爬虫sql之爬取数据存储到mysql的piplelines.py配置
- Python 爬取蚂蜂窝旅游攻略 (+Scrapy框架+MySQL)
- hdu2024 C语言合法标识符(C语言)
- JAVA面试题----最长DNA序列--java实现
- (转)“在证券行业,技术不重要,不要过分强调!”
- BUAA OJ 722 Gzh之表达式求值
- java常见问题
- python+scrapy+mysql爬取故事网站
- caffe中将jpg数据转化为lmdb格式的文件
- 《新概念英语(新版)辅导丛书:新概念英语国际音标与语音语调教练》 --- 纰漏百出
- Excel 技巧百例:快速变换两列的值
- 数据结构之排序算法
- ubuntu中启动VIM,以及学习VIM
- 【线段树-单点更新区间最大值】hdu 1754
- python 封装 0726
- UVA --11218 KTV(DFS+回溯)