以前写爬虫都是直接手写获取response然后用正则匹配,被大佬鄙视之后现在决定开始学习scrapy
一、安装
pip install scrapy
二、创建项目
scrapy startproject tutorial
三、配置
在项目内的settings文件加入
FEED_EXPORT_ENCODING = 'utf-8'
用于爬取中文
四、第一个爬虫
在项目的spiders文件夹新建一个py文件作为爬虫的程序
import scrapy class unicom_spider(scrapy.Spider): name="unicom" start_urls=["https://www.cnblogs.com/luozx207/"] def parse(self,response): # filename= response.url.split('/')[-2] # with open(filename,'wb') as f: # f.write(response.body) for title in response.xpath('//a[@class="postTitle2"]/text()').extract(): print title print len(response.xpath('//a[@class="postTitle2"]'))
这个爬虫爬的是我的博客列表,目的是输出所有随笔的标题
xpath('//a[@class="postTitle2"]/text()').extract():
'//a[@class="postTitle2"]会找出所有class中有“postTitle2”的a元素,text()会显示内容
最终结果: