python爬虫---js加密和混淆,scrapy框架的使用.

python爬虫---js加密和混淆,scrapy框架的使用. 一丶js加密和js混淆 js加密

​ 对js源码进行加密,从而保护js代码不被黑客窃取.(一般加密和解密的方法都在前端)

# 反解密 js混淆 # 目的: 为了缩小js体积,加快http传输速度 ,混淆的目的是保护代码 · 合并多个js文件 · 去除js代码里面的空格和换行 · 压缩js里面的变量名 · 剔除掉注释 二丶SCRAPY爬虫框架 概述scrapy框架特点 - 高性能的网络请求 - 高性能的数据解析 - 高性能的持久化存储 - 深度爬取 - 全栈爬取 - 分布式 - 中间件 - 请求传参 下载与安装 - 环境的安装: - mac/linux:pip install scrapy - window: - pip install wheel - 下载twisted ~gohlke/pythonlibs/#twisted - 进入下载目录,执行 pip install Twisted‑17.1.0‑cp35‑cp35m‑win_amd64.whl - pip install pywin32 - pip install scrapy 基本使用

​ 创建项目

- 新建一个工程:scrapy startproject ProName - 目录结构: - spiders(包):空包 - settings:配置文件 - 不遵从robots - UA伪装 - 日志等级的指定 - cd ProName:进入到工程目录中 - 在spiders(爬虫文件夹)中创建一个爬虫文件 - scrapy genspider spiderName - 编写代码:主要的代码会编写在爬虫文件中 - 执行工程:scrapy crawl spiderName

​ scrapy目录结构

- 项目名 - 同名项目文件夹 - spiders 文件夹 - init.py - items.py - middlewares.py - pipelines.py - settings.py - scrapy.cfg

​ scrapy数据解析

# scrapy 可以使用 xpath进行解析 # extract_first() 获取 读取文本并获得索引为0的字符串 # extract() 获取文本 content = div.xpath(\'.//div[@class="link-detail"]/a/text()\').extract_first()

​ scrapy数据存储

# 基于终端进行持久化存储 - 只可以将parse方法的返回值存储到本地的磁盘文件(指定形式后缀)中 - scrapy crawl spiderName -o filePath # 基于管道持久化存储 (**) - 在items注册存储的字段 (Filed万能字段,包含大部分数据类型) - 在piplelines文件 编写管道类 ,并在settings配置文件进行注册\'ITEM_PIPELINES\' - 编码流程 - 1.在爬虫文件中进行数据解析 - 2.在item类中定义相关的属性 - 3.将解析到的数据存储到一个item类型的对象中 - 4.将item类型的对象提交给管道 (yiled item) - 5.管道类的process_item方法负责接受item,接受到后可以对item实现任意形式的持久化存储操作 - 6.在配置文件中开启管道 - 一个管道类对应一种平台的持久化存储 ## 两种方式 # 基于 本地的管道存储 class ChoutiproPipeline(object): # 重写父类的方法, 只执行一次 fp = None def open_spider(self, spider): print(\'开始爬虫~~~~\') self.fp = open(\'./本地持久化存储文件.txt\', \'w\', encoding=\'utf-8\') def process_item(self, item, spider): author = item[\'author\'] content = item[\'content\'] self.fp.write(author + \':\' + content + \'\n\') return item def close_spider(self, spider): print(\'爬虫结束~~~\') self.fp.close() # 基于 mysql的管道存储 class MySqlChoutiproPipeline(object): conn = None cursor = None def open_spider(self, spider): print(\'创建数据库连接~~\') # 建立数据库连接 self.conn = pymysql.Connection(host=\'127.0.0.1\', port=3306, db=\'scrapy_db1\', user=\'root\', password=\'123\',charset=\'utf8\') # pymysql.Connection(host=\'127.0.0.1\', port=3306, user=\'root\', password=\'123\', db=\'spider\', charset=\'utf8\') def process_item(self, item, spider): authro = item[\'author\'] content = item[\'content\'] sql = \'insert into chouti values ("%s","%s")\' %(authro ,content) self.cursor = self.conn.cursor() try: self.cursor.execute(sql) self.conn.commit() # 提交 except Exception as e: print(e) self.conn.rollback() # 回滚 return item def close_spider(self,spider): self.cursor.close() self.conn.close()

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zypgdj.html