python爬虫Scrapy框架爬取小红书图片频道
导读:在spiders目录中新建`img_spider.py`文件,来实现我们的爬虫。首先导入需要的模块:python import scrapy from scrapy.http import Request然后定义爬虫类ImgSpider,继...
在spiders目录中新建`img_spider.py`文件,来实现我们的爬虫。首先导入需要的模块:
python
import scrapy
from scrapy.http import Request
然后定义爬虫类ImgSpider,继承Scrapy的Spider类:
python
class ImgSpider(scrapy.Spider):
name = 'img'
allowed_domains = ['xiaohongshu.com']
在`start_requests`方法中构造初始请求,爬取小红书的图片频道:
python
def start_requests(self):
start_url = 'https://www.xiaohongshu.com/explore?channel_id=homefeed.fashion_v3'
yield Request(url=start_url, callback=self.parse)
解析函数`parse`里面提取图片链接并递归爬取:
python
def parse(self, response):
img_urls = response.xpath('//img[@class="lazied"]/@data-src').getall()
for url in img_urls:
yield Request(url, callback=self.img_parse)
# 递归爬取下一页
next_page = response.xpath('//a[@class="next"]/@href').get()
if next_page:
yield Request(url=next_page, callback=self.parse)
在`img_parse`里面下载图片:
python
def img_parse(self, response):
img_name = response.url.split("/")[-1]
with open(img_name, 'wb') as f:
f.write(response.body)
我们可以通过管道将图片保存到指定目录中。在`pipelines.py`中编写管道:
python
class ImgPipeline(object):
def process_item(self, item, spider):
img_name = item['img_name']
img_data = item['img_data']
with open(f'images/{
img_name}
', 'wb') as f:
f.write(img_data)
并在settings.py中启用:
python
ITEM_PIPELINES = {
'xiaohongshu.pipelines.ImgPipeline': 300,
}
最后我们运行爬虫,它将递归爬取小红书中的图片:
scrapy crawl img
Scrapy会按照我们定义的逻辑,先爬取首页,提取图片链接,然后发送图片链接请求,获取图片数据后保存。循环往复直到爬取完指定范围内的页面。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: python爬虫Scrapy框架爬取小红书图片频道
本文地址: https://pptw.com/jishu/504593.html