nodejs使用electron抓取网络请求

1.安装并启动electron项目

git clone https://github.com/electron/electron-quick-start
cd electron-quick-start
npm install
npm start

2.修改index.html文件,加入

<webview src="https://www.baidu.com" partition="persist:github"></webview>

3.在index.html中加入

<script>
      function test() {
        const remote = require('electron').remote;	// 获取remote
        const net = remote.require('electron').net;	// 获取net用于发送请求
        const session = remote.session;		// 获取全局session
        var ses = session.fromPartition('persist:github');	// 获取webview的session
        const request = net.request({
          method: 'GET',
          url: 'https://www.baidu.com',
          session: ses,
          useSessionCookies: true
          // partition: 'persist:github'
        });
        request.setHeader("Referer","https://www.off---white.com/");
        request.setHeader("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) electron-quick-start/1.0.0 Chrome/87.0.4280.88 Electron/11.1.0 Safari/537.36");
        request.on('response', (response) => {
          console.log(`STATUS: ${response.statusCode}`);

          response.on('end', () => {
            console.log('No more data in response.');
          });

          response.on('data', (chunk) => {
            console.log(`BODY: ${chunk}`);
          });


        });

        request.end();


      }
    </script>

4.net的参数是clientrequest
ClientRequest实现了Writable Stream接口, 因此是一个EventEmitter类型.
ClientRequest格式:
参数
(Object | String) -如果 选项 是一个String类型, 它被解释为请求的URL.
如果它是一个Object类型, 那么它可以通过以下属性指定一个HTTP请求

method String (可选) - HTTP请求方法. 默认为GET方法.
url String (可选) - 请求的URL. 必须在指定了http或https的协议方案的独立表单中提供.
session Session (optional) - The Session instance with which the request is associated.
partition String (可选) - 与请求相关联的partition名称. 默认为空字符串. session选项优先于partition选项. 因此, 如果session是显式指定的, 则partition将被忽略.
useSessionCookies Boolean (optional) - Whether to send cookies with this request from the provided session. This will make the net request's cookie behavior match a fetch request. 默认值为 false.
protocol String (可选) - 在"scheme:"表单中的协议方案. 目前支持的值为'http:' 或者'https:'. 默认为'http:'.
host String (可选) - 作为连接提供的服务器主机,主机名和端口号'hostname:port'.
hostname String (可选) - 服务器主机名.
port Integer (可选) - 服务器侦听的端口号.
path String (可选) - 请求URL的路径部分.
redirect String (可选) - 请求的重定向模式. 可选值为 follow, error 或 manual. 默认值为 follow. 当模式为error时, 重定向将被终止. When mode is manual the redirection will be cancelled unless request.followRedirect is invoked synchronously during the redirect event.

options 属性,如 protocol, host, hostname, port 和 path,在 URL 模块中会严格遵循 Node.js 的模式
例如,我们可以创建与github.com相同的请求如下:

const request = net.request({
  method: 'GET',
  protocol: 'https:',
  hostname: 'github.com',
  port: 443,
  path: '/'
})

实例事件

response事件
response 收到的消息
表示HTTP响应消息的对象

login事件
返回:

authInfo Object
isProxy Boolean
scheme String
host String
port Integer
realm String
callback Function - 回调函数
username String (optional)
password String (optional)

当身份验证代理请求用户认证时触发
用户证书会调用 callback方法:
username String
password String

request.on('login', (authInfo, callback) => {
  callback('username', 'password')
})

提供空的凭证将取消请求,并在响应对象上报告一个身份验证错误:

request.on('response', (response) => {
  console.log(`STATUS: ${response.statusCode}`);
  response.on('error', (error) => {
    console.log(`ERROR: ${JSON.stringify(error)}`)
  })
})
request.on('login', (authInfo, callback) => {
  callback()
})

finish事件
在 request 最终的 chunk 数据后写入 request 后触发

abort事件
当 request请求被中止时发出。如果request 请求已经关闭, abort中止事件将不会被触发

error事件
返回:
error Error -提供失败信息的错误对象。
当 net网络模块没有发出网络请求时会触发。
通常情况下,当 request请求对象发出一个 error错误事件时,一个 close关闭事件会随之发生,并且不会提供响应对象。

close事件
作为HTTP 的 request-response 中的最后一个事件发出。
close事件表明,在request或response 对象中不会发出更多的事件

redirect事件
返回:

statusCode Integer
method String
redirectUrl String
responseHeaders Record<String, String[]>
Emitted when the server returns a redirect response (e.g. 301 Moved Permanently). Calling request.followRedirect will continue with the redirection. If this event is handled, request.followRedirect must be called synchronously, otherwise the request will be cancelled

实例属性

request.chunkedEncoding

实例方法
request.setHeader(name, value)
name String - 额外的 HTTP 头名称.
value String - An extra HTTP header value.
添加一个额外的 HTTP 头。 The header name will be issued as-is without lowercasing. 它只能在第一次写入之前调用。 在第一次写入后调用此方法将引发错误。 如果传递的值不是 String, 则会调用 toString () 方法来获取最终值。
request.getHeader(name)
name String - 指定一个额外的头名称.
Returns String - The value of a previously set extra header name.

request.removeHeader(name)
name String - 指定一个额外的头名称.
删除以前设置的额外头名称。此方法只能在首次写入之前调用。尝试在第一次写入后调用它会引发错误

request.write(chunk[, encoding][, callback])
chunk (String | Buffer) - 请求主体数据的一个块。如果是字符串, 它将使用指定的编码转换Buffer。
encodingString(可选)-用于将字符串块转换为Buffer对象。默认值为 “utf-8”。
callback Function (可选)-在写操作结束后调用。
callback 实质上是为了保持与 Node.js API 的相似性而引入的虚拟函数。 在将 chunk 内容传递到 Chromium 网络层之后, 在下一个 tick 中异步调用。 与 Node.js 实现相反, 不保证 chunk 内容在调用 callback 之前已经被刷新。
向请求正文中添加一个数据块。 第一次写操作可能导致在线路上发出请求头。 在第一次写入操作后, 不允许添加或删除自定义标头
request.end([chunk][, encoding][, callback])
chunk (String | Buffer) (可选)
encoding String (可选)
callback Function (可选)
发送请求数据的最后一个块。将不允许后续的写入或结束操作。finish 事件将在结束操作后发出
request.abort()
取消正在进行的 HTTP 事务。 如果请求已发出 close 事件, 则中止操作将不起作用。 否则正在进行的事件将发出 abort 和 close 事件。 此外, 如果有一个正在进行的响应对象, 它将发出 aborted 事件。

request.followRedirect()
Continues any pending redirection. Can only be called during a ‘redirect’ event

request.getUploadProgress()
返回 Object:

active Boolean - Whether the request is currently active. If this is false no other properties will be set
started Boolean - Whether the upload has started. If this is false both current and total will be set to 0.
current Integer - The number of bytes that have been uploaded so far
total Integer - The number of bytes that will be uploaded this request

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

97年的典藏版

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值