scrapy网页跳转后进行数据爬取

因为一开始的网站爬取的是一个href,所以需要去跳转一下,即发一个Request

<a href="https://XXX.com.cn/w/2018-11-24/doc-ihpevhck4340972.html">你好</a>

以下是自己的代码:

def parse(self, response):
    href_set = []
    list = response.xpath("//div[@style='display:none;']//li/a/@href").extract()    #获取href
    for i in range(0, 50, 1):   # 留下前50条数据
        href_set.append(list[i])
    for href in href_set:
        yield scrapy.Request(url=href, callback=self.new_parse)
        #就是这个Request请求了一个新的url,完成之后回调new_parse函数,进一步处理

def new_parse(self, response):
    myitem = TutorialItem()
    myitem['article_title'] = response.xpath("//h1[@class='main-title']/text()").extract()
    myitem['article_content'] = response.xpath("//div[@class='article']//p/text()").extract()
    # 获取第一张图片,可能无图
    myitem['article_image'] = response.xpath("//div[@class='img_wrapper']//img/@src").extract_first()
    # 把自己的item抛出给pipeline
    yield myitem

整体的思路就是通过parse的自动调用去获得href,之后用Request请求获取新网页内容,进一步处理。

如果爬的网页有 n 层href,那就调用 n 次Request,直到请求到自己想要获得数据的网页才进行爬取处理,不然就一直Request,进行跳转访问(我的只有一层href,即调一次href)

其实内建函数parse的原理也类似

猜你喜欢

转载自blog.csdn.net/changer_WE/article/details/84556184