我将使用scrapy框架进行爬取 http://www.imooc.com/course/list 这个网站的 第一页的封面图片
①首先使用命令行生成一个scrapy模板,要提前cd到需要存放的路径
(我这里放的是E盘,scrapy_Test是生成的文件夹名称)
在E盘里就生成了一个名字为scrapy_Test的文件夹
②然后使用pycharm直接打开这个文件夹
③右击spider,新建一个MySpider.py 文件
④然后右击scrapy_Test创建一个start.py的文件
⑤然后在start.py中添加如下代码:其中 scrapy crawl MySpider 是一个cmd命令
注意:"MySpider"与MySpider.py中name一致
⑥打开MySpider.py文件,添加如下代码(注释已经很详细,不过多解释)
import scrapy
import re
from scrapytest.items import Item
class MySpider(scrapy.Spider):
name = "MySpider" #这个name是我们在start.py中填写的MySpider,必须一致
start_urls = ["http://www.imooc.com/course/list"] #这里是一个url列表,可以放多条url
def parse(self, response):
item = Item()
html = response.text #返回response的HTML
cont = re.findall(r'data-original="(.*?)"', html) #通过正则表达式提取封面图片的url
for i in range(len(cont)):
# scrapy.Request发请求时,必须要完整的URL信息,所以补齐 http:
item['img_url'] = 'http:'+cont[i] #存入item(在item中要定义 img_url = scrapy.Field() )
yield item #yield是一个生成器,每次处理一个
此时在items中就已经存储了我们所需要的url,然后我们开始实现下载的步骤
⑦在scrapy_Test下新建一个ImgPipelines.py
import scrapy
from scrapy.pipelines.images import ImagesPipeline
from scrapy.exceptions import DropItem
class ImgPipeline(ImagesPipeline):
#通过抓取的图片url获取一个Request用于下载
def get_media_requests(self, item, info):
#返回Request根据图片图片url下载
yield scrapy.Request(item['img_url'])
#当下载请求完成后执行该方法
def item_completed(self, results, item, info):
#获取下载地址
img_path = [x['path'] for ok, x in results if ok]
#判断是否成功
if not img_path:
raise DropItem("Item contains no images")
#将地址存入item
item['img_path'] = img_path #这里的 img_path 已经在item中定义
return item
⑧然后在piplines.py中,将url存储成json文件
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
import json
class ScrapytestPipeline(object):
def __init__(self):#创建并打开文件 data.json
self.file = open('data.json','w',encoding='utf-8')
def process_item(self, item, spider):#对数据进行操作
#读取item的数据,ensure_ascii = False (防止写入的是ASCII字符码)
line = json.dumps(dict(item),ensure_ascii=False) + '\n'
#写入文件
self.file.write(line)
return item
⑨最后我们需要配置我们的setting文件了
# 在请求头中可以添加基本信息进行反反爬虫
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
}
ROBOTSTXT_OBEY = False #取消robots协议,避免爬取失败(我们这里爬取量小,可以适量不遵守robots协议)
ITEM_PIPELINES = {
'scrapytest.pipelines.ScrapytestPipeline': 100,
'scrapytest.ImgPipelines.ImgPipeline': 1, # 我们的ImgPipelines要添加上去,才能运行这个模块
}
IMAGES_STORE = 'E:\\img\\' #这里是存储图片的路径
在目录下会生成data.json文件,存储我们的url信息
这个是爬取到的图片
这个是data.json 文件内容