nodejs selenium 添加cookie

让人想犯罪 __ 提交于 2020-08-08 10:00:09

文档

https://www.selenium.dev/selenium/docs/api/javascript/module/selenium-webdriver/index_exports_WebDriver.html

 

自动播放b站视频

直接使用脚本点击会报错, 因为并无用户操作

虽然注入cookie成功, 但是只能播放, 无法使用cookie将视频加入到播放历史中

const firefox = require('selenium-webdriver/firefox');
const chrome = require('selenium-webdriver/chrome');
const cookie = "==="
const {Builder, By, Key, until, Options} = require('selenium-webdriver');

const os = require('os');
let platform = os.platform();
console.log(platform)

const WAIT_TIME = 1000

const url = 'https://www.bilibili.com/video/BV1sA411i7tz'

function waitTime(n) {
  return new Promise(resolve => setTimeout(
    () => resolve()
    , n
  ))
}

// 使用脚本点击会报错
const script = `
let v = document.getElementsByClassName('bilibili-player-video')[0]
v.click()

return new Promise(resolve => setTimeout(
  () => resolve()
  , 1000
)) 
`

async function play(url) {
  const chromeType = platform === 'win32' ? 'chrome' : 'firefox'
  let options = chromeType === 'chrome' ? new chrome.Options() : new firefox.Options()
  let driver = await new Builder().forBrowser(chromeType)
    .setFirefoxOptions(options)
    .build(options);

  let op = driver.manage()

  for (let i of cookie.split(';')) {
    let [name, value] = i.split('=')
    name = name.trim()
    value = value.trim()
    console.log(name, value)
    op.addCookie(
      {
        name,
        value
      }
    )
  }

  console.log(op.getCookies())
  try {
    await driver.get(url);
    await driver.get('https://www.bilibili.com/video/BV1Cp4y1U7fp?spm_id_from=333.851.b_7265706f7274466972737431.8')
    console.log(op.getCookies())

    await waitTime(WAIT_TIME)
    await driver.executeScript(script)
    let v = await driver.findElement(By.className('bilibili-player-video'))
    console.log('list', v)
    await v.click()
    await waitTime(WAIT_TIME * 1500)
  } catch (e) {
    console.log('==>', e)
    return -1
  } finally {
    await driver.quit();
  }
}


play(url)

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!