> scrapy startproject imgPro
> cd imgPro
> scrapy genspider tupian www.xxx.com
ROBOTSTXT_OBEY = False
LOG_LEVEL = "ERROR"
USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36 Edg/90.0.818.51'
自行手动进行请求发送.
tupian.py
import scrapy
from ..items import ImgproItem
class TupianSpider(scrapy.Spider):
name = 'tupian'
# allowed_domains = ['www.xxx.com']
# 起始url
start_urls = ['https://pic.netbian.com/4kmeinv/']
def parse(self, response):
# 获取li列表
li_list = response.xpath('//div[@class="slist"]/ul[1]/li')
# 遍历列表
for li in li_list:
# 获取名称
name = li.xpath("./a/b/text()").extract_first()
# 实例化item对象
item = ImgproItem()
# 把名称传递给item
item['name'] = name
yield item
import scrapy
from ..items import ImgproItem
class TupianSpider(scrapy.Spider):
name = 'tupian'
# allowed_domains = ['www.xxx.com']
# 起始url
start_urls = ['https://pic.netbian.com/4kmeinv/']
# 创建通用url模板
url = "https://pic.netbian.com/4kmeinv/index_%d.html"
nume = 2
def parse(self, response):
# 获取li列表
li_list = response.xpath('//div[@class="slist"]/ul[1]/li')
# 遍历列表
for li in li_list:
# 获取名称
name = li.xpath("./a/b/text()").extract_first()
print(name)
# 循环请求url
if self.nume <= 5:
# 拼接新的url
new_url = format(self.url%self.nume)
self.nume += 1
# 手动请求发送
yield scrapy.Request(url=new_url, callback=self.parse)
请求流程 :
1. 当程序第一次执行的时候, 对起始url发请求, 让scrapy自动调用parse方法进行数据解析
2. for循环进行名称的获取并打印, for循环执行完毕以后, 执行if语句
3. if条件满足, 拼接第二页的url, scrapy.Request手动进行请求发送
4. 手动请求发送以后, 会回调parse函数
5. parse再次被调用, 解析第二页的数据
6. 以此类推, 直到if条件不满足