Scrapy 如何用Requst进行递归网址爬取

这里用到Python的scapy 框架中的basic 模板

因为用basic模板不会自动跟进link,所以要用Request进行递归爬取网页

在爬取网页时会遇到一些小问题需要处理:

1,url带有中文字符

需求分析:

顶级url:需要爬取0-10的url

https://www.xxxcf.com/htm/girllist10/2.htm(2.htm-10.htm)

次级url:

进入顶级url后是这样的页面:

《Scrapy 如何用Requst进行递归网址爬取》 image

然后每一个url需要继续跟进 ,获得其底级url:

进入底级url:

《Scrapy 如何用Requst进行递归网址爬取》 image

这个底级的jpg图片的url才是我们需要retrive的数据:

import scrapy
from first.items import FirstItem
import urllib
”’
add browser head
”’
from scrapy.http import Request

class SkySpider(scrapy.Spider):
name = “name”
allowed_domains = [“xxxcf.com”]
#反扒机制–request
def start_requests(self):
ua={‘User-Agent’:’Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like GeChrome/63.0.3239.84 Safari/537.36′}
yield Request(‘https://www.xxxcf.com/htm/girllist10/0.htm’,headers=ua)

这里第一个parse是吧顶级url压入request栈,全部入栈后,对栈内的url调用pars2方法

def parse(self, response):
    for i in range(1,8):
        url = 'https://www.xxxcf.com/htm/girllist10/'+str(i)+'.htm'
        yield Request(url,self.parse2)

《Scrapy 如何用Requst进行递归网址爬取》 image.png

在parse2中,response里有所有的顶级url对应的页面,所以对每个url对应页面进行再次获取次级url

def parse2(self, response):
    for sel in response.xpath('//li'):
        url2 = sel.xpath("a[@target='_blank']/@href").extract()
        for i in url2:
            #https://www.xxxcf.com/htm/girl10/2200.htm
            yield Request('https://www.xxxcf.com'+i, self.parse3)

《Scrapy 如何用Requst进行递归网址爬取》 image.png

在parse3的response中有次级url对应的页面,所以对每个次级url对应的底级页面抓取jpg的url

def parse3(self, response):
    for sel2 in response.xpath('//div'):
        item = FirstItem()
        #<div class ="content" > < br / > < img src="https://com/girl/TuiGirl/110/01.jpg" / > < br >
        item['link'] = sel2.xpath("img/@src").extract()
        yield item

这样就进行了对url的连续深层爬取。

    原文作者:sky_memory
    原文地址: https://www.jianshu.com/p/0c39d8cd1820
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞