美文网首页
Python爬虫学习9-非登录爬取网站

Python爬虫学习9-非登录爬取网站

作者: MingSha | 来源:发表于2017-04-02 14:59 被阅读0次

    http://blog.jobbole.com/all-posts/页面为例

    1、提取列表页

    获取一个列表页

    首页获得页面文章列表,使用css选择器进行:
    article_list = response.css('#archive .floated-thumb .post-thumb a::attr(href)').extract()

    Paste_Image.png

    在文件中引入Request库
    from scrapy.http import Request使用Request进行对上节函数的调用

        def parse(self, response):
            """
            1、获取文章列表页url并交给scrapy进行解析
            2、获取下一个文章列表页
            """
            article_list = response.css('#archive .floated-thumb .post-thumb a::attr(href)').extract()
            for article in article_list:
                yield Request(url=article, callback=self.parse_detail)
    

    最后一句为对每个url调用parse_detail进行解析。这里的article的网址为带完整域名的格式,如果不是完整域名,则需要对域名进行拼接成完成域名进行解析。
    首先要引入from urllib import parse,通过parse自带的parse.urljoin()进行拼接,代码为:yield Request(url=parse.urljoin(response.url, article), callback=self.parse_detail)

    获取下一个列表 页

    每个列表页都有“下一页”链接,通过extract_first("")来得到下一页链接,如果为空则表示完成。

            next_list = response.css('.next.page-numbers::attr(href)').extract_first("")
            if next_list:
                yield Request(url=parse.urljoin(response.url, next_list), callback=self.parse)
    

    2、对具体内容页面提取

    解析函数如下:

    
        def parse_detail(self, response):
            title = response.css('div.entry-header h1::text').extract_first()
            create_date = response.css('p.entry-meta-hide-on-mobile::text').extract()[0].replace('·','').strip()
            fav_nums = response.css("span.bookmark-btn::text").extract()[0]
            match_re = re.match(".*?(\d+).*", fav_nums)
            if match_re:
                fav_nums = match_re.group(1)
            comment_nums = response.css("a[href='#article-comment'] span::text").extract()[0]
            match_re = re.match(".*?(\d+).*", comment_nums)
            if match_re:
                comment_nums = match_re.group(1)
            content = response.css(".entry").extract()[0]
            tag_list = response.css('p.entry-meta-hide-on-mobile a::text').extract()
            tag_list = [e for e in tag_list if not e.strip().endswith("评论")]
            tags = ",".join(tag_list)
            print(title, create_date, fav_nums, comment_nums, tags)
    

    通过以上代码,即可将相应内容提取出来了。

    Paste_Image.png

    相关文章

      网友评论

          本文标题:Python爬虫学习9-非登录爬取网站

          本文链接:https://www.haomeiwen.com/subject/bnrgottx.html