- response是一个
<class 'scrapy.http.response.html.HtmlResponse'>
对象,可以执行‘xpath’和‘css语法来提取元素’ - 提取出来的数据是一个‘SelectorList’或者是一个‘Selector’对象,如果想要获取其中的字符串,那么应该执行getall或者get方法
- getall方法:获取selector中的所有文本,返回的是一个列表
- get方法:获取的是selector中的第一个文本,返回的是一个str类型
- 如果数据解析回来,要传给pipline处理,那么可以使用yiled来返回,或者是收集所有的items,最后统一使用items返回
- item:建议在item.py中定义好模型,以后就不要使用字典
- pipline:这个是专门用来保存数据的,其中三个方法经常用到。
open_spider(self,spider):当爬虫被打开的时候执行
process_item(self,item_spider):当爬虫有item传过来的时候被调用
close_spider(self,spider):当爬虫关闭的时候会被调用
要激活pipline,应在settings.py中,ITEM_PIPELINES = { 'qsbk.pipelines.QsbkPipeline': 300, }
JsonLinesItemExporter和JsonItemExporter:
保存json数据的时候,可以使用这两个类,让操作变的更简单
- JsonItemExporter:这个是每次把数据添加到内存中,最后统一写的磁盘中,好处是:存储的是数据是一个满足json规则的数据,坏处是如果数据量比较大则耗费时间比较长。
- JsonLinesItemExporter:这个是每次调用‘export_item’的时候就把这个item存储到磁盘中,坏处是每一个字典是一行,整个文件不是一个满足json格式的文件,好吃是每次处理数据的时候就直接存储到了硬盘中,这样不会耗内存,数据也比较安全。
糗事百科爬虫全过程
- 将settings里面的ROBOTSTXT_OBEY =True改成False
- 加入请求头:
DEFAULT_REQUEST_HEADERS = {
‘Accept’: ‘text/html,application/xhtml+xml,application/xml;q=0.9,/;q=0.8’,
‘Accept-Language’: ‘en’,
“User-Agent”: “Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36”
}- DOWNLOAD_DELAY = 1
- ITEM_PIPELINES = {
‘qsbk.pipelines.QsbkPipeline’: 300,
}
#利用终端来运行比较麻烦
from scrapy import cmdline
cmdline.execute("scrapy crawl qsbk_spider".split())
qsbk_spider.py
# -*- coding: utf-8 -*-
import scrapy
from qsbk.items import QsbkItem
class QsbkSpiderSpider(scrapy.Spider):
name = 'qsbk_spider'
#允许的域名,限制爬虫的范围,不会到处乱跑
allowed_domains = ['qiushibaike.com']
#开始的url,是一个列表,可以传递多个
start_urls = ['https://www.qiushibaike.com/text/page/1/']
def parse(self, response):
#Selevtorlist
divs= response.xpath("//div[@id='content-left']/div")
for div in divs:
author=div.xpath(".//h2/text()").get().strip()
content=div.xpath(".//div[@class='content']//text()").getall()
content=" ".join(content).strip()
#duanzi={"author":author,"content":content}
item=QsbkItem(author=author,content=content)
yield item
next_url=response.xpath("//ul[@class='pagination']/li[last()]/a/@href").get()
if not next_url:
return
else:
yield scrapy.Request("https://www.qiushibaike.com"+next_url,callback=self.parse)
items.py
import scrapy
class QsbkItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
author=scrapy.Field()
content=scrapy.Field()
piplines.py存储json数据的三种方式
import json
# class QsbkPipeline(object):
# def __init__(self):
# self.fp=open("duanzi.json","w",encoding="utf-8")
# def open_spider(self,spider):
# print("爬虫开始了")
# def process_item(self, item, spider):
# item_json=json.dumps(dict(item),ensure_ascii=False)
# self.fp.write(item_json+"\n")
# return item
# def close_spider(self,spider):
# print("爬虫结束了")
from scrapy.exporters import JsonItemExporter
# class QsbkPipeline(object):
# def __init__(self):
# self.fp=open("duanzi.json","wb")
# self.exporter=JsonItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
# self.exporter.start_exporting()
# def open_spider(self,spider):
# print("爬虫开始了")
# def process_item(self, item, spider):
# self.exporter.export_item(item)
# return item
# def close_spider(self,spider):
# self.exporter.finish_exporting()
# self.fp.close()
# print("爬虫结束了")
from scrapy.exporters import JsonLinesItemExporter
class QsbkPipeline(object):
def __init__(self):
self.fp=open("duanzi.json","wb")
self.exporter=JsonLinesItemExporter(self.fp,ensure_ascii=False,encoding='utf-8')
self.exporter.start_exporting()
def open_spider(self,spider):
print("爬虫开始了")
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
def close_spider(self,spider):
self.exporter.finish_exporting()
self.fp.close()
print("爬虫结束了")
在糗事百科爬虫中我们的爬虫是继承scrapy.Spider类的,这也是基本的scrapy框架爬虫,在这个爬虫中我们自己在解析完整个页面后再获取下一页的url,然后重新发送了一个请求,而使用CrawlsSpider类可以帮助我们对url提出条件,只要满足这个条件,都进行爬取,CrawlSpider类继承自Spider,它比之前的Spider增加了新功能,即可以定义url的爬取规则,而不用手动的yield Request。
微信小程序社区CrawlScrapy爬虫
创建爬虫项目:scrapy genspider -t crawl【爬虫名字】【域名】
打开cmd,定位到scrapy所在位置,运行scrapy startproject wxapp建立新的爬虫项目
定位到刚才建立的爬虫项目:创建scrapy genspider -t crawlwxapp_spider wxapp-union.com爬虫
如下图所示,则表示创建成成功。
同样的需要新建一个用来运行的python文件start.py
from scrapy import cmdline
cmdline.execute("scrapy crawl wxapp_spider".split())
打开wxapp_spider
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from lxml import etree
from wxapp.items import WxappItem
class WxappSpiderSpider(CrawlSpider):
name = 'wxapp_spider'
allowed_domains = ['wxapp-union.com']
#起始链接
start_urls = ['http://www.wxapp-union.com/portal.php?mod=list&catid=2&page=1']
rules = (
#Rule(LinkExtractor(allow=r'Items/'), callback='parse_item', follow=True),
#不需要获取详情页,就不用写callback,需要将满足当前条件的url再进行跟进,所以设置follow=True
Rule(LinkExtractor(allow=r'.+mod=list&catid=2&page=\d'), follow=True),
#需要获取详情页callback='parse_item',不需要将满足当前条件的url再进行跟进,所以设置follow=True
Rule(LinkExtractor(allow=r'.+article-.+\.html'), callback='parse_item', follow=False),
)
def parse_item(self, response):
title_name = response.xpath('//h1[@class="ph"]/text()').get()
content= response.xpath('//p[@class="authors"]')
author=content.xpath('./a/text()').get()
time=content.xpath('./span/text()').get()
item=WxappItem(title_name=title_name,author=author,time=time)
yiled item
将获取到的数据存储为json格式
`打开items.py
import scrapy
class WxappItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
title_name= scrapy.Field()
author = scrapy.Field()
time = scrapy.Field()
from scrapy.exporters import JsonLinesItemExporter
class WxappPipeline(object):
def __init__(self):
self.fp = open("wxjc.json","wb")
self.exporter = JsonLinesItemExporter(self.fp, ensure_ascii=False, encoding='utf-8')
def process_item(self, item, spider):
self.exporter.export_item(item)
return item
def close_spider(self, spider):
self.fp.close()
注意:和糗事百科的爬虫一样,要对settings.py进行设置
用‘LinkExtractor’和‘Rule’这两个东西决定爬虫的具体走向
1.allow设置规则的方法:要能够限制在我们想要的url上id
2.关于follow: 如果爬取页面的时候,需要将满足当前条件的url再进行跟进,那么就设置为True,否则设置为False
3.关于callback: 如果url对应的页面,只是为了获取更多的url,并不需要里面的数据,那么可以不指定callback,如果想要获取url对应页面中的内容,那么久需要指定一个callback