一、先在MySQL中创建test数据库,和相应的site数据表

二、创建Scrapy工程

#scrapy startproject 工程名
scrapy startproject demo4

三、进入工程目录,根据爬虫模板生成爬虫文件

#scrapy genspider -l # 查看可用模板
#scrapy genspider -t 模板名 爬虫文件名 允许的域名
scrapy genspider -t crawl test sohu.com

四、设置IP池或用户代理(middlewares.py文件)

 # -*- coding: utf-8 -*-
# 导入随机模块
import random
# 导入有关IP池有关的模块
from scrapy.downloadermiddlewares.httpproxy import HttpProxyMiddleware
# 导入有关用户代理有关的模块
from scrapy.downloadermiddlewares.useragent import UserAgentMiddleware # IP池
class HTTPPROXY(HttpProxyMiddleware):
# 初始化 注意一定是 ip=''
def __init__(self, ip=''):
self.ip = ip def process_request(self, request, spider):
item = random.choice(IPPOOL)
try:
print("当前的IP是:"+item["ipaddr"])
request.meta["proxy"] = "http://"+item["ipaddr"]
except Exception as e:
print(e)
pass # 设置IP池
IPPOOL = [
{"ipaddr": "182.117.102.10:8118"},
{"ipaddr": "121.31.102.215:8123"},
{"ipaddr": "1222.94.128.49:8118"}
] # 用户代理
class USERAGENT(UserAgentMiddleware):
#初始化 注意一定是 user_agent=''
def __init__(self, user_agent=''):
self.user_agent = user_agent def process_request(self, request, spider):
item = random.choice(UPPOOL)
try:
print("当前的User-Agent是:"+item)
request.headers.setdefault('User-Agent', item)
except Exception as e:
print(e)
pass # 设置用户代理池
UPPOOL = [
"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393"
]

五、settngs.py配置

 COOKIES_ENABLED = False

 DOWNLOADER_MIDDLEWARES = {
# 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware':123,
# 'demo4.middlewares.HTTPPROXY' : 125,
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': 2,
'demo4.middlewares.USERAGENT': 1
} ITEM_PIPELINES = {
'demo4.pipelines.Demo4Pipeline': 300,
}

六、定义爬取关注的数据(items.py文件)

 # -*- coding: utf-8 -*-
import scrapy
# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html class Demo4Item(scrapy.Item):
name = scrapy.Field()
link = scrapy.Field()

七、爬虫文件编写(test.py)

 # -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from demo4.items import Demo4Item class TestSpider(CrawlSpider):
name = 'test'
allowed_domains = ['sohu.com']
start_urls = ['http://www.sohu.com/'] rules = (
Rule(LinkExtractor(allow=('http://news.sohu.com'), allow_domains=('sohu.com')), callback='parse_item',
follow=False),
# Rule(LinkExtractor(allow=('.*?/n.*?shtml'),allow_domains=('sohu.com')), callback='parse_item', follow=False),
) def parse_item(self, response):
i = Demo4Item()
i['name'] = response.xpath('//div[@class="news"]/h1/a/text()').extract()
i['link'] = response.xpath('//div[@class="news"]/h1/a/@href').extract()
#i['description'] = response.xpath('//div[@id="description"]').extract()
return i

八、管道文件编写(pipelines.py)

 # -*- coding: utf-8 -*-
import pymysql
import json
# 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.html class Demo4Pipeline(object):
def __init__(self):
# 数据库连接
self.conn = pymysql.connect(host='localhost', user='root', password='', database='chapter17', charset='utf8')
self.cur = self.conn.cursor() def process_item(self, item, spider):
# 排除空值
for j in range(0, len(item["name"])):
nam = item["name"][j]
lin = item["link"][j]
print(type(nam))
print(type(lin))
# 注意参数化编写
sql = "insert into site(name,link) values(%s,%s)"
self.cur.execute(sql,(nam,lin))
self.conn.commit()
return item
def close_spider(self, spider):
self.cur.close()
self.conn.close()

九、总结

1.注意在测试完数据库正常运行时,再开始写入数据,当然,在sql参数化处理的过程中,注意格式,千万不要弄错了

python框架Scrapy中crawlSpider的使用——爬取内容写进MySQL的更多相关文章

  1. python框架Scrapy中crawlSpider的使用

    一.创建Scrapy工程 #scrapy startproject 工程名 scrapy startproject demo3 二.进入工程目录,根据爬虫模板生成爬虫文件 #scrapy genspi ...

  2. scrapy中使用selenium来爬取页面

    scrapy中使用selenium来爬取页面 from selenium import webdriver from scrapy.http.response.html import HtmlResp ...

  3. Scrapy 框架 CrawlSpider 全站数据爬取

    CrawlSpider 全站数据爬取 创建 crawlSpider 爬虫文件 scrapy genspider -t crawl chouti www.xxx.com import scrapy fr ...

  4. scrapy框架之CrawlSpider全站自动爬取

    全站数据爬取的方式 1.通过递归的方式进行深度和广度爬取全站数据,可参考相关博文(全站图片爬取),手动借助scrapy.Request模块发起请求. 2.对于一定规则网站的全站数据爬取,可以使用Cra ...

  5. scrapy进阶(CrawlSpider爬虫__爬取整站小说)

    # -*- coding: utf-8 -*- import scrapy,re from scrapy.linkextractors import LinkExtractor from scrapy ...

  6. python爬虫之爬取糗事百科并将爬取内容保存至Excel中

    本篇博文为使用python爬虫爬取糗事百科content并将爬取内容存入excel中保存·. 实验环境:Windows10   代码编辑工具:pycharm 使用selenium(自动化测试工具)+p ...

  7. python爬虫爬取内容中,-xa0,-u3000的含义

    python爬虫爬取内容中,-xa0,-u3000的含义 - CSDN博客 https://blog.csdn.net/aiwuzhi12/article/details/54866310

  8. Crawlspider的自动爬取

    引子 : 如果想要爬取 糗事百科 的全栈数据的方法 ? 方法一 : 基于scrapy框架中的scrapy的递归爬取进行实现(requests模块递归回调parse方法) . 方法二 : 基于Crawl ...

  9. [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息

    [Python爬虫] 使用 Beautiful Soup 4 快速爬取所需的网页信息 2018-07-21 23:53:02 larger5 阅读数 4123更多 分类专栏: 网络爬虫   版权声明: ...

随机推荐

  1. iOS 9应用开发教程之ios9中实现button的响应

    iOS 9应用开发教程之ios9中实现button的响应 IOS9实现button的响应 button主要是实现用户交互的.即实现响应.button实现响应的方式能够依据加入button的不同分为两种 ...

  2. php.ini配置与中国间隔12小时间设置方法

    打开php.ini 配置文件找到date.timezone把=号后面的参数改成这个date.timezone = Etc/GMT+4即可,这样与中国的时间误差即能达到12小时

  3. 教程:VS2010 之TFS入门指南(转载)

    [原文发表地址] Tutorial: Getting Started with TFS in VS2010 [原文发表时间] Wednesday, October 21, 2009 1:00 PM 本 ...

  4. Windows 2003 远程桌面

  5. debian下运行netstat失败

    如果提示:bash: netstat: command not found 说明没有安装netstat工具,而该工具在 net-tools 工具包内. apt-get install net-tool ...

  6. CentOS安装自动补全安装包

    CentOS7标准版有这个功能,但是CentOS6却没有,其实很简单: 1.安装bash-completion yum install bash-completion 2.保存一下最新的缓存 yum ...

  7. Linux网络流量监控与分析工具Ntopng

    Ntopng工具 Ntopng是一个功能强大的流量监控.端口监控.服务监控管理系统 能够实现高效地监控多台服务器网络 Ntopng功能介绍 Ntop提供了命令行界面和web界面两种工作方式,通过web ...

  8. Tomcat 学习进阶历程之Tomcat架构与核心类分析

    前面的http及socket两部分内容,主要是为了后面看Tomcat源代码而学习的一些网络基础.从这章開始.就開始实际深入到Tomcat的'内在'去看一看. 在分析Tomcat的源代码之前,准备先看一 ...

  9. JavaScript函数内部修改全局变量的问题【一道面试题】

    JavaScript函数内部修改全局变量的问题 今天 10:44梵天莲华 | 浏览 23 次  Javascript编程语言函数 修改标签 代码如下,为什么加了 function a(){};这个函数 ...

  10. linux学习笔记6--命令mv

    mv命令是move的缩写,可以用来移动文件或者将文件改名(move (rename) files),是Linux系统下常用的命令,经常用来备份文件或者目录. mv命令用来对文件或目录重新命名,或者将文 ...