如何在scrapy框架下,用python实现爬虫自动跳转页面来抓去网页内容

如题所述

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

我们通过获取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,该页中下一页按钮的审查元素是:

我们不能通过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方法会自动获取里面的请求
温馨提示:答案为网友推荐,仅供参考
相似回答