zoukankan      html  css  js  c++  java
  • scrapy框架_2数据解析案例_最新糗事百科案例

    scrapy 配置文件setting.py

    
    BOT_NAME = 'TestOne'
    
    SPIDER_MODULES = ['TestOne.spiders']
    NEWSPIDER_MODULE = 'TestOne.spiders'
    
    
    #UA伪装
    USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
    
    
    #robots协议是否遵从
    ROBOTSTXT_OBEY = False
    #显示指定类型的日志信息
    LOG_LEVEL="ERROR"
    
    

    scrapy创建好的spiders子目录中创建好的爬虫文件内容

    import scrapy
    
    
    class FirstSpider(scrapy.Spider):
    
        #爬虫文件的名称:就是爬虫源文件唯一标识
        name = 'first'
        #允许的域名:用来限制start_urls那些url可以进行请求发送
        # allowed_domains = ['www.baidu.com','https://www.sogou.com/',]
        #启始url的列表:该列表存放的url会被scrapy自动请求发送
        start_urls = ['https://www.qiushibaike.com/text/',]
    
        #用于数据解析:response参数表示就是请求成功后对应的响应对象
        def parse(self, response):
            number = 0
            div_list=response.xpath('//*[@id="content"]/div/div[2]/div')
            for div in div_list:
                #xpath返回的是列表,但是列表元素一定是Selector类型的对象
                #extract可以将Selector对象中的data参数存储的字符串提取出来
                #第一种写法
                author = div.xpath('./div[1]/a[2]/h2//text()')[0].extract()
                # 第二种写法
                #author = div.xpath('./div[1]/a[2]/h2//text()').extract_first()
    
    
                # 列表调用了extract之后,则表示将列表中的Selector对象中的data对的的字符串提取出来
                content = div.xpath('./a/div/span//text()').extract()
    
    
                #格式化
                content=' '.join(content).replace('
    ','')
                print(content,author)
    
    
  • 相关阅读:
    python day01
    Mac上安装pexpect
    raid
    SSL证书制作
    linux grep命令详解
    第一轮迭代小组成员分数分配
    M1事后分析报告(Postmortem Report)
    软件发布说明
    测试报告
    week 9 scenario testing
  • 原文地址:https://www.cnblogs.com/SkyRabbit/p/13715289.html
Copyright © 2011-2022 走看看