- scrapy是一套比较成熟的python爬虫框架,是使用python开发的快速,高层次的信息爬取框架,可以高效的爬取web页面并提取我们想要的结构化数据。
- 安装scrapy
pip install scrapy
通过对应的版本来安装scrapy,安装最新版就行,已经可以支持python3。
- 安装环境 python3.7+scrapy最新版
如果你的pip命令较老,可以通过命令升级pip
python -m pip install --upgrade pip
一般会有提示告诉你怎么升级
Scrapy项目实战- 爬取新浪新闻 1.创建一个scrapy爬虫项目
2.项目创建好之后,下面首先修改项目中的items.py文件:
3.然后我们还需要修改pipelines.py 文件,我们将对应的信息存储到数据库中,注意:这里是使用mysql,小编通过本项目来讲解用python操作mysql,大家也可以通过excel存储,这里就不过多讲了;我们需要事先设计好数据库,然后根据设计好的数据库进行相应的处理,如下所示:
首先导入 pymysql
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html import pymysql # useful for handling different item types with a single interface from itemadapter import ItemAdapter class MysqlpjtPipeline: def __init__(self): self.conn = pymysql.connect(host='127.0.0.1',user='root',passwd='***',db='pydb') def process_item(self, item, spider): name = item['name'][:30] key = item['keywd'] sql = "insert into mytb(title,keywd) VALUES ('"+name+"','"+key+"')" self.conn.query(sql) self.conn.commit() return item def close_spider(self,spider): self.conn.close()
一定要记得添加commit,不然数据是插入无效的,很多小伙伴都会遗忘
- 我们也可以通过python来创建一个对应的数据库,如下所示:
import pymysql # 连接mysql,创建数据库 conn = pymysql.connect(host="127.0.0.1",user='root',password='***') conn.query("create database pydb") # 进入pydb数据库,创建表mytb结构 conn1 = pymysql.connect(host="127.0.0.1",user='root',password='***',db='pydb') # 设计表结构,字段类型 conn1.query("create table mytb(title char(20) NOT NULL,keywd char (30))")
- 设置好settings.py启动对应的pipelines
# Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'mysqlpjt.pipelines.MysqlpjtPipeline': 300, }
5.我们基于crawl爬虫模板创建一个名为xinlan 的爬虫文件,如下所示:
可以通过观察多个新闻页面URL地址,大家可以自行观察其规律并写出对应的正则表达式,这里我帮大家已经写好了
.?/[0-9]{4}.[0-9]{2}.[0-9]{2}.doc-.?shtml
6.接下来,最后一步,编写xinlan.py爬虫文件:
import scrapy from scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Rule from mysqlpjt.items import MysqlpjtItem class TestSpider(CrawlSpider): name = 'xinlan' allowed_domains = ['sina.com.cn'] start_urls = ['http://sina.com.cn/'] rules = ( Rule(LinkExtractor(allow=('.*?/[0-9]{4}.[0-9]{2}.[0-9]{2}.doc-.*?shtml')), callback='parse_item', follow=True), ) def parse_item(self, response): i = MysqlpjtItem() i["name"] = response.xpath('/html/head/title/text()').get() i['keywd'] = response.xpath('/html/head/meta[@name="keywords"]/@content').get() #item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get() #item['name'] = response.xpath('//div[@id="name"]').get() #item['description'] = response.xpath('//div[@id="description"]').get() return i
编写好文件之后,通过以下命令运行:
scrapy crawl xinlan