zoukankan      html  css  js  c++  java
  • 爬蟲實踐其二

    動態獲取

    from selenium import webdriver
    from time import sleep
    bro = webdriver.Chrome(executable_path='./chromedriver')
    bro.get('http://www.baidu.com')
    
    text = bro.find_element_by_id('kw')
    text.send_keys('時間')
    sleep(1)
    button = bro.find_element_by_id('su')
    button.click()
    

      

    phantomjs插件的使用

    from selenium import webdriver
    from time import sleep
    
    bro = webdriver.PhantomJS(executable_path='/Users/Administrator/First_jupyter/phantomjs-2.1.1-windows/bin/phantomjs')
    url = 'https://movie.douban.com/typerank?type_name=%E5%96%9C%E5%89%A7&type=24&interval_id=100:90&action='
    bro.get(url)
    sleep(1)
    bro.save_screenshot('./1.png')
    
    js = 'window.scrollTo(0,document.body.scrollHeight)'
    
    bro.execute_script(js)
    sleep(1)
    
    bro.save_screenshot('./2.png')
    

      

    Scrapy使用

    a) 概念:为了爬取网站数据而编写的一款应用框架,出名,强大。所谓的框架其实就是一个集成了相应的功能且具有很强通用性的项目模板。(高性能的异步下载,解析,持久化……)

    b) 安装:

    1. linux mac os:pip install scrapy
    2. win:
      1. pip install wheel
      2. 下载twistedhttps://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted

            pip install 下载好的框架.whl

          3.pip install pywin32

          4.pip install scrapy

    c) 基础使用: 使用流程

        1.创建一个工程:scrapy startproject 工程名称     #scrapy startproject firstBlood  

        2.在工程目录下创建一个爬虫文件

        3.cd 工程                    #cd firstBlood

        4.scrapy genspider 爬虫文件的名称 起始的url     #scrapy genspider first www.qiushibaike.com

        5.对应的文件中编写爬虫程序来完成爬虫的相关操作6.配置文件的编写(settings

         19行:对请求载体的身份进行伪装

         22行:不遵从robots协议

    # Crawl responsibly by identifying yourself (and your website) on the user-agent
    USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
    
    # Obey robots.txt rules
    ROBOTSTXT_OBEY = False

        6.执行 scrapy crawl 爬虫文件的名称   --nolog(阻止日志信息的输出)                  #scrapy crawl first

    class FirstSpider(scrapy.Spider):
        #爬虫文件的名称:通过爬虫文件的名称可以指定的定位到某一个具体的爬虫文件
        name = 'first'
        #允许的域名:只可以爬取指定域名下的页面数据
        allowed_domains = ['www.qiushibaike.com']
        #起始url:当前工程将要爬取的页面所对应的url
        start_urls = ['http://www.qiushibaike.com/']
    
        #解析方法:对获取的页面数据进行指定内容的解析
        #response:根据起始url列表发起请求,请求成功后返回的响应对象
        #parse方法的返回值:必须为迭代器或者空
        def parse(self, response):
    
            print(response.text)#获取响应对象中的页面数据
    

      

        def parse(self, response):
            div_list = response.xpath('//div[@id="content-left"]/div')
            data_list = []
            for div in div_list:
                # title = div.xpath('./div/a[2]/h2/text()').extract_first()
                # print(title)
                content = div.xpath('.//div[@class="content"]/span/text()').extract_first()
                #不是直屬的div 就用 //  兩個表示,如果是直屬就用一個 /
    
                content = div.xpath('.//div[@class="content"]/span/text()').extract_first()
                print(content)
    

      

    持续化存储:

    其一:

    用指令,首先在parse方法里面返回一个值,

    再使用终端指令,---> scrapy crawl 爬虫文件名称 -o 磁盘文件.后缀,

    scrapy crawl tang -o tang.csv --nolog
    

      

    其二:

    基于管道操作

    i.items:存储解析到的页面数据
    ii.pipelines:处理持久化存储的相关操作
    iii.代码实现流程:
      1.将解析到的页面数据存储到items对象
      2.使用yield关键字将items提交给管道文件进行处理
      3.在管道文件中编写代码完成数据存储的操作
      4.在配置文件中开启管道操作

    item.py
    
    class TangItem(scrapy.Item):
        # define the fields for your item here like:
        # name = scrapy.Field()
        title1 = scrapy.Field()
        content1 = scrapy.Field()
    
    #先定义后名称key
    

      

        def parse(self, response):
            div_list = response.xpath('//div[@id="content-left"]/div')
            data_list = []
            for div in div_list:
                title = div.xpath('./div/a[2]/h2/text()').extract_first()
                # print(title)
                # content = div.xpath('.//div[@class="content"]/span/text()').extract_first()
                #不是直屬的div 就用 //  兩個表示,如果是直屬就用一個 /
                content = div.xpath('.//div[@class="content"]/span/text()').extract_first()
                item = TangItem()
                item['title1'] = title
                item['content1'] = content
    
                yield item
    
    #然后使用yield关键字传入管道中
    

      

    pipelines.py
    
    class TangPipeline(object):
        fp = None
        def open_spider(self,spider):
            self.fp = open('./text.txt','w',encoding='utf-8')
    
        def process_item(self, item, spider):
            title = item['title1']
            content = item['content1']
            self.fp.write(title+':'+content+'
    
    
    ')
            return item
    
        def close_spider(self,spider):
            print('爬蟲結束!')
            self.fp.close()
    
    #最后再在管道里面写相应的规则
    

      

    settings.py
    
    ITEM_PIPELINES = {
       'tang.pipelines.TangPipeline': 300,   #優先級,可以500 如此類推
    }
    
    终极最后在设置把这个注释打开
    

      

    最后终端运行 scrapy crawl tang

    使用lpush命令传入redis

    不知为何按照教程传入字典时会报错,后来改用列表方式传入后可以

    使用命令 scrapy crawl 文件名 --nolog   执行

    redis查看:range 数据名(如下是data)0 (起始位) -1 (末位)  ---->   lrange data 0 -1

    class FirstRedisPipeline(object):
        coon = None
        t = 0
        fuck = []
        def open_spider(self, spider):
            # self.fp = open('./text.txt', 'w', encoding='utf-8')
            try:
                self.coon = redis.Redis(host='127.0.0.1',port='6379')
                print('正在連接數據庫redis......')
            except:
                print('連接數據庫失敗')
    
        def process_item(self, item, spider):
            self.fuck = item['title']+":"+item['content']
            try:
                self.coon.lpush('data', self.fuck)       #data是传入的数据名字
                print('正在傳入數據到數據庫.......')
            except:
                print('出錯了')
            return item
    

    多个url数据爬取

    class TestPagesSpider(scrapy.Spider):
        name = 'Test_Pages'
        #allowed_domains = ['https://www.qiushibaike.com/text']
        start_urls = ['https://www.qiushibaike.com/text/']
        page_Num = 1
        url = 'https://www.qiushibaike.com/text/page/%d/'
    
        def parse(self, response):
            div_list = response.xpath('//*[@id="content-left"]/div')
    
            for div in div_list:
                title = div.xpath('./div[@class="author clearfix"]/a[2]/h2/text()').extract_first()
                content = div.xpath('.//div[@class="content"]/span/text()').extract_first()
                item = TomPagesItem()
                item['title'] = title
                item['content'] = content
    
                yield item
                # print('test2')
            if self.page_Num <= 13:                        #关键是这里要做一个判断
                print('爬取到了第%d页的页面数据' % self.page_Num)
                self.page_Num += 1
                new_url = format(self.url % self.page_Num)
                yield scrapy.Request(url=new_url, callback=self.parse)

      

    代理和cookie:

    如何发起post请求?

      一定要重写start_requests方法

        1.Request()方法中给method属性赋值成post

        2.FormRequest()进行post请求的发送

    代理:

    流程:

      1.下載中間件類的自制定

        a)object

        b)重寫process_request(self,request,spider)

      2.配置文件中進行下載中間件的開啟

      

    DOWNLOADER_MIDDLEWARES = {
       'post_scrapy.middlewares.MyProxy': 543,             #其中MyProxy修改成你重寫的方法名字
    }

    日誌:

    日志等级(种类)

    ERROR:错误

    WARNING:警告

    INFO:一般信息

    DEBUG:调试信息(默认)

    指定输入某一中日志信息:

    settings:LOG_LEVEL = ‘ERROR’

    将日志信息存储到制定文件中,而并非显示在终端里:

    settingsLOG_FILE = ‘log.txt’

    請求傳參:

    CrawlSpider:

    CrawlSpider其实是Spider的一个子类,除了继承到Spider的特性和功能外,还派生除了其自己独有的更加强大的特性和功能。其中最显著的功能就是”LinkExtractors链接提取器“。Spider是所有爬虫的基类,其设计原则只是为了爬取start_url列表中网页,而从爬取到的网页中提取出的url进行继续的爬取工作使用CrawlSpider更合适。

    創建:

      1.创建scrapy工程: scrapy startproject projectName

      2.创建爬虫文件:  scrapy genspider -t crawl spiderName www.xxx.com

     start_urls = ['https://www.id97.cc/index.php/vodshow/']
        link = LinkExtractor(allow=r'/dongman--------d+---2018.html')     #LinkExtractor其實就是一個鏈接選擇器
        rules = (
            Rule(link, callback='parse_item', follow=True),
        )

    分佈式爬蟲

  • 相关阅读:
    利用观察者模式 进行不同页面的传值
    axios请求处理
    百度地图实现鼠标绘制图形并获取相关数据
    web前端支付功能
    各种好用插件汇总(持续更新...)
    记录iview表单校验的"坑"
    JavaScript字符串方法
    2020面试汇总
    JavaScript作用域
    JavaScript原型到原型链
  • 原文地址:https://www.cnblogs.com/tyh-tesla/p/11183652.html
Copyright © 2011-2022 走看看