古人云博采众长,我们来看看其他人的爬虫是怎么学和用的:
安装Scrapy
pip install x.whl
,x
为 whl文件名,依次安装三个文件。简单快速的Scrapy
num1.py
的文件添加以下内容,使用命令行scrapy runspider num1.py -o 1.json
在文件当前所在目录下运行文件,表示使用Scrapy执行该爬虫并将输出数据保存为json文件。
- # -*- coding: utf-8 -*-
- # 文本编辑器编码要设置对,最好为UTF-8无BOM编码
- import scrapy
-
- class Num1Spider(scrapy.Spider):
- name = "num1" # 爬虫命名,在项目中有用
- allowed_domains = ["jianshu.com"] # 允许爬取的域名
- domain = 'http://jianshu.com' # 自己设置的基础域名变量
-
- headers = {
- "User-Agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
- } # 请求头
- base_url = 'http://www.jianshu.com/collections/16/notes?order_by=added_at&page=%d'
- # 关于此处url,参看新手向爬虫(一)
- num = 0 # 页数
-
- def start_requests(self): # 默认的开始函数,用于提供要爬取的链接
- # url = self.base_url % self.num
- while self.num < 4000: # 程序员专题总页数小于4000,共花费212.975027秒
- self.num += 1
- yield scrapy.Request(self.base_url % self.num,
- headers = self.headers,
- callback = self.parse)
-
- def parse(self, response): # 默认的回调函数,用于链接下载完毕后调用来处理数据
-
- for index,i in enumerate(response.css(".title a::text").extract()):
- if "爬虫" in i or "爬取" in i:
- like = response.css("a + span::text").extract()[index].replace(' · 喜欢 ', '')
- url = self.domain + response.css('.title a::attr(href)').extract()[index]
- yield {"title" : i, "like": like, "url": url}
-
-
- ######################## Debug ###############################
- # from scrapy.shell import inspect_response
- # inspect_response(response, self)
- # 将以上两句插入回调函数中任意位置,即可在运行过程中中断打开交互命令行,用于调试查看响应内容
- ######################## Run ###############################
- # scrapy runspider num1.py -o 1.json
文本后处理
- # -*- coding: utf-8 -*-
- import json
-
- with open('1.json','r') as f:
- data = json.load(f)
- data = sorted(data, key =lambda x: int(x['like']), reverse=True)
- # 以喜欢数对文章进行排序
- with open('1.md', 'w') as m:
- m.write('### 爬虫文章 in 简书程序员专题:\n')
- for i in data:
- m.write('- *like*:**{like}** - [{title}]({url})\n'.format(**i))
- # **i 表示解包字典
Scrapy官方文档
转载于:https://www.jianshu.com/p/dcd6438ce4c7
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态