Python爬虫学习6:scrapy入门(一)爬取汽车评论并保存到csv文件

一、scrapy 安装:可直接使用Anaconda Navigator安装, 也可使用pip install scrapy安装



二、创建scrapy 爬虫项目:语句格式为 scrapy startproject project_name


生成的爬虫项目目录如下,其中spiders是自己真正要编写的爬虫。



三、爬取腾讯新闻并保存到csv文件

      1. 只爬取一个页面:在spiders目录下创建spider程序car_comment_spider.py 并编辑代码如下:

import scrapy

class CarCommentSpider(scrapy.Spider):
    name = 'CarComment'             # 蜘蛛的名字
    # 指定要抓取的网页
    start_urls = ['https://koubei.16888.com/117870/']      
    
    # 网页解析函数
    def parse(self, response):
        for car in response.xpath('/html/body/div/div/div/div[@class="mouth_box"]/dl'):   # 遍历xpath
            advantage = car.xpath('dd/div[2]/p[1]/span[@class="show_dp f_r"]/text()').extract_first()
            disadvantage = car.xpath('dd/div[2]/p[2]/span[2]/text()').extract_first()
            sums = car.xpath('dd/div[2]/p[3]/span[2]/text()').extract_first()
            support_num = car.xpath('dd/div/div[@class="like f_r"]/a/text()').extract_first()
           
            print('优点:',advantage)
            print('缺点:',disadvantage)
            print('综述:',sums)
            print('支持人数:',support_num)

        在cmd命令行中执行scrapy runspider car_comment_spider.py




2. 爬取某个车型的所有评论并保存到csv文件

    (1)自行组建不同页面的url: 根据网页url的规律可设置

            start_urls = ['https://koubei.16888.com/117870/0-0-0-%s' % p for p in range(1,125)]

import scrapy

class CarCommentSpider(scrapy.Spider):
    name = 'CarComment'             # 蜘蛛的名字
    # 指定要抓取的网页, 从第1页到第124页,程序会自动解析每个url
    start_urls = ['https://koubei.16888.com/117870/0-0-0-%s' % p for p in range(1,125)]      
    
    # 网页解析函数
    def parse(self, response):
        for car in response.xpath('/html/body/div/div/div/div[@class="mouth_box"]/dl'):   # 遍历xpath
            advantage = car.xpath('dd/div[2]/p[1]/span[@class="show_dp f_r"]/text()').extract_first()
            disadvantage = car.xpath('dd/div[2]/p[2]/span[2]/text()').extract_first()
            sums = car.xpath('dd/div[2]/p[3]/span[2]/text()').extract_first()
            support_num = car.xpath('dd/div/div[@class="like f_r"]/a/text()').extract_first()
           
            print('优点:',advantage)
            print('缺点:',disadvantage)
            print('综述:',sums)
            print('支持人数:',support_num)
            
            if len(advantage) != 0 and len(disadvantage) != 0 and len(sums) != 0 and len(support_num) != 0:
                yield {'advantage':advantage, 'disadvantage':disadvantage, 'sums':sums, 'support_num':support_num}



(2)从每一页的代码解析找到下一页的url

        下一页的url在a标签中,此处存在多个a标签,故需要从中找到下一页对应的a标签



import scrapy

class CarCommentSpider(scrapy.Spider):
    name = 'CarComment'             # 蜘蛛的名字
    # 指定要抓取的网页, 从第1页到第124页,程序会自动解析每个url
    start_urls = ['https://koubei.16888.com/117870/0-0-0-1/']      
    
    # 网页解析函数
    def parse(self, response):
        for car in response.xpath('/html/body/div/div/div/div[@class="mouth_box"]/dl'):   # 遍历xpath
            advantage = car.xpath('dd/div[2]/p[1]/span[@class="show_dp f_r"]/text()').extract_first()
            disadvantage = car.xpath('dd/div[2]/p[2]/span[2]/text()').extract_first()
            sums = car.xpath('dd/div[2]/p[3]/span[2]/text()').extract_first()
            support_num = car.xpath('dd/div/div[@class="like f_r"]/a/text()').extract_first()
           
            print('优点:',advantage)
            print('缺点:',disadvantage)
            print('综述:',sums)
            print('支持人数:',support_num)
            
            if advantage is not None and disadvantage is not None and sums is not None and support_num is not None:
                yield {'advantage':advantage, 'disadvantage':disadvantage, 'sums':sums, 'support_num':support_num}
        
        n = len(response.xpath('/html/body/div/div/div/div/div[@class="page"]/a'))   
        for i in range(1,n+1):     # 遍历每个a元素,获取下一页的url
            text = response.xpath('/html/body/div/div/div/div/div[@class="page"]/a['+str(i)+']/text()').extract_first()
            if text == '下一页':
                next_page = response.xpath('/html/body/div/div/div/div/div[@class="page"]/a['+str(i)+']/@href').extract_first()
                next_page = response.urljoin(next_page)        # 将相对地址转换为绝对地址

                yield scrapy.Request(next_page, callback=self.parse)    # next_page继续进行spider解析


爬虫(Web Crawler)是种自动化程序,用于从互联网上收集信息。其主要功能是访问网页、提取数据存储,以便后续分析或展示。爬虫通常由搜索引擎、数据挖掘工具、监测系统等应用于网络数据抓取的场景。 爬虫的工作流程包括以下几个关键步骤: URL收集: 爬虫个或多个初始URL开始,递归或迭代地发现新的URL,构建个URL队列。这些URL可以通过链接分析、站点地图、搜索引擎等方式获取。 请求网页: 爬虫使用HTTP或其他协议向目标URL发起请求,获取网页的HTML内容。这通常通过HTTP请求库实现,如Python中的Requests库。 解析内容: 爬虫对获取的HTML进行解析,提取有用的信息。常用的解析工具有正则表达式、XPath、Beautiful Soup等。这些工具帮助爬虫定位和提取目标数据,如文本、图片、链接等。 数据存储: 爬虫将提取的数据存储到数据库、文件或其他存储介质中,以备后续分析或展示。常用的存储形式包括关系型数据库、NoSQL数据库、JSON文件等。 遵守规则: 为避免对网站造成过大负担或触发反爬虫机制,爬虫需要遵守网站的robots.txt协议,限制访问频率和深度,模拟人类访问行为,如设置User-Agent。 反爬虫应对: 由于爬虫的存在,些网站采取了反爬虫措施,如验证码、IP封锁等。爬虫工程师需要设计相应的策略来应对这些挑战。 爬虫在各个领域都有广泛的应用,包括搜索引擎索引、数据挖掘、价格监测、新闻聚合等。然而,使用爬虫需要遵守法律和伦理规范,尊重网站的使用政策,确保对被访问网站的服务器负责。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值