一、先在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. LAMP架构三

    PHP相关配置 1.查找php配置文件/usr/local/php/bin/php -i或者phpinfo() [root@bogon admin]# /usr/local/php/bin/php - ...

  2. JVM虚拟机(二):堆、栈、方法区概念区别

    Java 堆 Java堆是和Java应用程序关系最密切的内存空间,几乎所有的对象都放在其中,并且Java堆完全是自动化管理,通过垃圾收集机制,垃圾对象会自动清理,不需自己去释放. 根据垃圾回收机制的不 ...

  3. atitit.php 流行框架 前三甲为:Laravel、Phalcon、Symfony2 attilax 总结

    atitit.php 流行框架 前三甲为:Laravel.Phalcon.Symfony2 attilax 总结 1. ,最流行的PHP框架前三甲为:Laravel.Phalcon.Symfony2. ...

  4. [转载]ecmall语言包程序

    [转载]ecmall语言包程序 (-- ::) 转载▼ 标签: 转载 收藏了 原文地址:ecmall语言包程序作者:我思故我在 执行顺序 登陆后台后 最先执行的文件是 default.app.php ...

  5. plist 与 JOSN的解析

  6. FileMonitorKit 文件操作监控工具

    本人业余时间写的一款文件操作监控工具,功能稳定.效果非常好,有兴趣的网友能够下载玩玩. 下载地址: 32位:http://pan.baidu.com/s/1o64ZFIi          FileM ...

  7. 基于Redis实现延迟队列

    背景 在后端服务中,经常有这样一种场景,写数据库操作在异步队列中执行,且这个异步队列是多进程运行的,这时如果对同一资源进行写库操作,很有可能产生数据被覆盖等问题,于是就需要业务层在更新数据库之前进行加 ...

  8. windows7 mongodb 安装急遇到的问题

    偶尔上一次博客园,才发现自己这么久没有写东西了.今天更新一篇. 作为前端开发者,node.js 无非是一个强心剂.有了node.js 后端开发变得不需要再搞另一门语言,一个javascript 就能搞 ...

  9. C. Magic Five

    C. Magic Five Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 524288/262144K (Java/Other) Tot ...

  10. EasyUI combobox 加载JSON数据《一》

    Action返回 JSON 格式如下: jsonResult = { total=7,rows=[ {TEXT=技术支持, ID=402894ca4419acf1014419b148a10000}, ...