一、先在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. Livereload介绍

    Livereload可理解为即时刷新,在前端开发中,开发人员在编写或调试html/js/css代码后须要从编辑器切换到浏览器.再刷新浏览器才干看到页面变化,这样的十分频繁的操作在一定程度上影响了工作效 ...

  2. The server has either erred or is incapable of performing the requested operation. (HTTP 500)

    感谢朋友支持本博客,欢迎共同探讨交流,因为能力和时间有限,错误之处在所难免,欢迎指正. 假设转载.请保留作者信息. 博客地址:http://blog.csdn.net/qq_21398167 原博文地 ...

  3. 170. Rotate List【medium】

    Given a list, rotate the list to the right by k places, where k is non-negative.   Example Given 1-& ...

  4. redis命令_ZRANGE

    ZRANGE key start stop [WITHSCORES] 返回有序集 key 中,指定区间内的成员. 其中成员的位置按 score 值递增(从小到大)来排序. 具有相同 score 值的成 ...

  5. python学习之endswith()

    定义: Python endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False.可选参数"start"与"end&q ...

  6. linux下的which

    which命令用来查找并打印可执行文件的绝对路径. 他会根据PATH环境变量定义的路径来依此查找可执行文件. 需要注意的是,指向可执行文件的链接文件在查找中会被忽略. 比如env命令: ll /usr ...

  7. Oracle VM VirtualBox虚拟机导出教程

    Oracle VM VirtualBox虚拟机导出教程 | 浏览:583 | 更新:2015-01-31 11:21 1 2 3 4 5 6 7 分步阅读 有时我们需要把Oracle VM Virtu ...

  8. 安全DNS

    国内首家云安全DNS:(114DNS)114.114.114.114114.114.115.115 将 DNS 地址设为114.114.114.119 和 114.114.115.119 ,拦截钓鱼病 ...

  9. java递归排序

    public class TestNativeOutOfMemoryError{ static int[] aa = new int[] {1, 2, 3, 4}; static int[] bb = ...

  10. java -jar Incompatible argument to function

    原因分析:jar包版本问题 解决方法:到工程中查看代码引用的jar包版本是多少,然后升级jar包,就可以了!