scrapy分页抓取网页(内建函数parseRequest请求获取新网页内容进一步处理,获爬取处理)

优采云 发布时间: 2022-02-03 17:28

  scrapy分页抓取网页(内建函数parseRequest请求获取新网页内容进一步处理,获爬取处理)

  因为最初抓取的网站是一个href,所以需要跳转到它,也就是发送一个Request

  你好

  这是我的代码:

  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,则调用Request n次,直到爬取到要获取数据的网页,否则保持Request和跳转访问(我的只有一层)href,即调整href一次)

  其实内置函数parse的原理是类似的

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线