python+scrapy爬虫时如何自动翻页获取内容

自动翻页分为两种情况:此处所举例子有一定的时效性,请具体情况具体分析,方法类似

(1)一种是像我之前爬虫新京报网的新闻,下一页的url可以通过审查元素获得,第一页的网址是http://www.bjnews.com.cn/news/list-43-page-1.html
在第一页的时候,下一页按钮的审查元素是

《python+scrapy爬虫时如何自动翻页获取内容》

我们通过获取next_pages = response.xpath(‘//div[@id=”page”]/a[@class=”next”]/@href’).extract()[0]
,便可以得到下一页的url,next_page = “http://www.bjnews.com.cn” + next_pages,

这一部分的完整代码为:

page_link=set() #保存下一页页面url

content_link=set() #保存页面内所有可获得的url

rules={‘page’:LinkExtractor(allow=(r’^http://www.bjnews.com.cn/\w+/2016/\d{2}/\d{2}/\d{6}.html
))}

start_urls={‘http://www.bjnews.com.cn/news/list-43-page-1.html’}

def parse(self, response):

#爬取一个页面内的所有url链接

    for link in self.rules[‘page’].extract_links(response):

        if link.url not in self.content_link:

            self.page_link.add(link.url)

            yield scrapy.Request(link.url, callback=self.parse_item)

#自动获取下一页的url

    next_pages = response.xpath(‘//div[@id=”page”]/a[@class=”next”]/@href’).extract()[0]

    if next_pages:

        next_page = “http://www.bjnews.com.cn” + next_pages

        self.page_link.add(next_page)

        yield scrapy.Request(next_page, callback=self.parse)

(2)第二种情况,就是在下一页的审查元素中没有提供url链接,需要自己分析,在这里依然举个例子,比如搜狐新闻http://news.sohu.com/guojixinwen.shtml,该页中下一页按钮的审查元素是:

《python+scrapy爬虫时如何自动翻页获取内容》

我们不能通过href来直接过得下一页的url,需要自己手动获得,那现在我们来分析

第二页的url:http://news.sohu.com/guojixinwen_5230.shtml,第三页的http://news.sohu.com/guojixinwen_5229.shtml,最后一页的http://news.sohu.com/guojixinwen_5132.shtml,由此可以分析出这一共100页的url,是http://news.sohu.com/guoneixinwen_”+i+”.shtml”,其中i是从5230到5132倒序排列的,也就是说通过for循环,就可以获得这100页的所有url,完整代码如下:在这里给大家加一个新的方法的使用start_request,该方法就是子定义start_urls,把所有自定义的url放到page_link中,self.make_requests_from_url方法会自动获取里面的请求

page_link = set()

content_link=set()

rules = {‘page’:LinkExtractor(allow=(r’^http://news.sohu.com/\d{8}/\w+.shtml
))

def start_requests(self):

for i in range(5230, 5133)[::-1]:

url = “http://news.sohu.com/guoneixinwen_”+str(i)+”.shtml”

self.page_link.add(url)

for url in self.page_link:

yield self.make_requests_from_url(url)

}

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