一、创建Scrapy工程

 #scrapy startproject 工程名
scrapy startproject demo3

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

 #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配置

 #========================================

 # 设置IP池和用户代理

 # 禁止本地Cookie
COOKIES_ENABLED = False # 下载中间件配置指向(注意这里的工程名字是"demo3",指向DOWNLOADER_MIDDLEWARES = {
# 'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware':123,
# 'demo3.middlewares.HTTPPROXY' : 125,
'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': 2,
'demo3.middlewares.USERAGENT': 1
} # 管道指向配置(注意这里的工程名字是"demo3",指向ITEM_PIPELINES = {
'demo3.pipelines.Demo3Pipeline': 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 Demo3Item(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 demo3.items import Demo3Item 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 = Demo3Item()
i['name'] = response.xpath('//div[@class="news"]/h1/a/text()').extract()
i['link'] = response.xpath('//div[@class="news"]/h1/a/@href').extract()
return i

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

 # -*- coding: utf-8 -*-
import codecs
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 Demo3Pipeline(object):
def __init__(self):
self.file = codecs.open("E:/workspace/PyCharm/codeSpace/books/python_web_crawler_book/chapter17/demo3/1.json", "wb", encoding='utf-8') def process_item(self, item, spider):
for j in range(0, len(item["name"])):
name = item["name"][j]
link = item["link"][j]
datas = {"name": name, "link": link}
i = json.dumps(dict(datas), ensure_ascii=False)
line = i + '\n'
self.file.write(line)
return item
def close_spider(self, spider):
self.file.close()

八、测试(scrapy crawl test )之后,生成了1.json文件

python框架Scrapy中crawlSpider的使用的更多相关文章

  1. python框架Scrapy中crawlSpider的使用——爬取内容写进MySQL

    一.先在MySQL中创建test数据库,和相应的site数据表 二.创建Scrapy工程 #scrapy startproject 工程名 scrapy startproject demo4 三.进入 ...

  2. python框架Django中MTV框架之VIew(业务控制器)

    MTV框架之VIew(业务控制器) 关注公众号"轻松学编程"了解更多. 1.什么是视图 视图层=路由表(urls.py)+视图函数(views.py) 其角色相当于MVC中的Con ...

  3. python框架Django中MTV框架之Template(模板/界面)

    MTV框架之Template(模板/界面) 关注公众号"轻松学编程"了解更多. 1.模板目录位置 应用下 不需要注册 无法跨应用地进行复用 工程下 需要注册 settings.py ...

  4. python框架Django中MTV之Model(数据模型)

    MTV框架之Model(数据模型) 关注公众号"轻松学编程"了解更多. 1.连接MySQL数据库 项目中的settings.py设置范例 # 配置数据库 DATABASES = { ...

  5. python框架Django中的MTV架构

    MTV架构 关注公众号"轻松学编程"了解更多. ​ 通过V对M和T进行连接,用户通过T(界面)对服务器进行访问(发送请求),T把请求传给V(调度),V调用M(数据模型)获取数据,把 ...

  6. scrapy 中crawlspider 爬虫

    爬取目标网站: http://www.chinanews.com/rss/rss_2.html 获取url后进入另一个页面进行数据提取 检查网页: 爬虫该页数据的逻辑: Crawlspider爬虫类: ...

  7. python框架django中结合vue进行前后端分离

    一:创建django项目 1.django-admin startproject mysite # 创建mysite项目 2.django-admin startapp app01# 创建app01应 ...

  8. python框架Scrapy报错TypeError: 'float' object is not iterable解决

    原因是:Twisted版本高了. 解决办法: 只要把Twisted库降级到16.6.0即可: pip3 install Twisted== 注:Twisted16..0安装后,会自动卸载高版本的Twi ...

  9. 教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

    本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感. Scr ...

随机推荐

  1. C#使用技巧之调用JS脚本(转)

    .创建个Winform项目. .在From1上增加一个文本框一个按钮. .在解决方案中创建一个test.js文件. test.js代码如下: function sayHello(str) { retu ...

  2. mybatis想要在控制台显示sql语句配置文件

    在src目录下创建一个properties文件 配置内容如下 log4j.rootLogger=debug,stdout,logfile log4j.appender.stdout=org.apach ...

  3. myeclipse中配置schemaLocation路径,实现xml文件自动提示

    在开发中,XML的xsi:schemaLocation路径都是指向网络,但是这个网络地址有时候很不给力导致工程检验XML格式缓慢.所以有必要再myeclipse中配置本地xsd文件路径,以免每次校验都 ...

  4. 百度语音识别demo:去掉离线识别功能

    如果离线识别功能不是必须的,则为了减小包体积,可按下面方法将官方demo中的离线功能去掉: 1,删除loadOfflineEngine调用.2,删除data和license文件夹. 如此可使包体积减少 ...

  5. 저장소system.runtime.remoting.messaging.callcontext

    https://msdn.microsoft.com/ko-kr/library/system.runtime.remoting.messaging.callcontext(v=vs.110).asp ...

  6. atitit.薄伽梵歌overview  attilax 读后感

    atitit.薄伽梵歌overview  attilax 读后感 1. 唯一一本记录神而不是神的代言人或者先知言论的经典 2 2. 篇章规模,字数 3 3. 内容摘要 3 4. 主要内容 3 4.1. ...

  7. 浏览器在线打开pdf

    https://www.cnblogs.com/Leo_wl/p/5735001.html#_label0 https://blog.csdn.net/li_cheng_liang/article/d ...

  8. 7-16 Bestcoder a Oracle

    Time Limit: 8000/4000 MS (Java/Others)    Memory Limit: 262144/262144 K (Java/Others)Total Submissio ...

  9. [转]Python定时任务框架APScheduler

    APScheduler是基于Quartz的 一个Python定时任务框架,实现了Quartz的所有功能,使用起来十分方便.提供了基于日期.固定时间间隔以及crontab类型的任务,并且可以 持久化任务 ...

  10. 原生javascript 实现的文本编辑器

    直接来干活上代码.就一个函数execCommand():自己百度一下. 在线预览 <!doctype html> <html> <head> <title&g ...