创建项目
scrapy startproject <项目名称>
生成一个爬虫
scrapy genspider <itcast 名称> <itcast.cn 域名>
提取数据
会生成以下一个文件,start_urls为爬取的url,prase为解析后返回的处理函数
import scrapy
class ItcastSpider(scrapy.Spider):
name = "itcast"
allowed_domains = ["itcast.cn"]
start_urls = ["http://www.acwing.com/activity"]
def parse(self, response):
with open("itcast.html", "wb") as f:
f.write(response.body)
保存数据
- pipelines.py 中处理来的数据,来一条数据执行一遍process_item函数
- 在settings.py中开启管道,
-
ITEM_PIPELINES = { # 项目名.文件名.类名:优先级 越小越优先 "myscrapy.pipelines.MyscrapyPipeline": 300, }
运行爬虫
scrapy crawl <爬虫名称>
数据建模
在采集数据想要封装成对象可以在Item.py中定义
class MyscrapyItem(scrapy.Item):
name = scrapy.Field()
title = scrapy.Field()
desc = scrapy.Field()
# 赋值时候
a = MyscrapyItem()
a['name'] = ....
翻页请求
- 找到下一页的url
- 构造url请求对象,传递给引擎
class ItcastSpider(scrapy.Spider):
name = "itcast"
allowed_domains = ["luogu.com.cn"]
start_urls = ["https://www.luogu.com.cn/problem/list?page=1"]
root_url = "https://www.luogu.com.cn/problem/"
def parse(self, response):
node_list = response.xpath('//ul/li')
for node in node_list:
item = MyscrapyItem()
item['title'] = node.xpath('./text()').get()
item['name'] = node.xpath('./a/text()').get()
item['url'] = self.root_url + node.xpath('./a/@href').get()
yield item
next_url = self.root_url + "list" + response.xpath('//div/a[2]/@href').get()
print(next_url)
if next_url != "https://www.luogu.com.cn/problem/list?page=11":
yield scrapy.Request(
url=next_url,
callback=self.parse
)
页面数据传递
在页面中再次进入页面采集数据,吧item传递过去
yield scrapy.Request(url=self.root_url + url, meta={'item': item}, callback=self.parseNext)
# 获取
item = response.meta['item']
getall 方法
# 获取全部的text使用getall
content_list = response.xpath('//div[@class="contson"]//text()').getall()
模拟登录携带cookie
重写start_requests方法,携带cookie
def start_requests(self):
url = self.start_urls[0]
temp = "cookieString"
cookie = {i.split('=')[0]: i.split('=')[1] for i in temp.split('; ')}
yield scrapy.Request(
url=url,
callback=self.parse,
cookies=cookie
)
模拟发送post方法
scrapy 会像浏览器一样保存你的登录状态