要将信息从客户端发送到服务器,您可以(例如)使用 jQuery ajax (http://api.jquery.com/jquery.ajax/) 或 axios (https://github.com/axios/axios) 使用用户名和密码向服务器发送 post 请求在体内。
以下是有关如何登录然后转到用户设置页面并从那里删除用户选择的语言的示例。它应该在 99% 的时间内工作,尽管我注意到 Twitter 有时会提供带有不同类选择器的不同加载页面,因此如果你希望它在 100% 的时间内工作,你必须适当地处理它。
在这种情况下,您将post 请求发送到/puppeteer 端点。 req.body 是您的ajax 请求的数据/正文,格式应为:{ username: 'username', password: 'password' }。如果您将headless参数设置为true,Puppeteer 将打开一个 Chromium 浏览器窗口,您可以在其中看到整个过程。
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.set('trust proxy')
const puppeteer = require('puppeteer')
const http = require('http')
app.post('/puppeteer', async (req, res) => {
const LOGIN_URL = `https://twitter.com/login`
const ACCOUNT_URL = `https://twitter.com/settings/account`
const CREDENTIALS = req.body
// Setting up Puppeteer
const browser = await puppeteer.launch({ headless: false })
const page = await browser.newPage()
await page.setViewport({ width: 1920, height: 926 })
// Go to login page
await page.goto(LOGIN_URL)
// Let's wait until submit button is available, without this you won't be able to login
await page.waitForSelector('.submit')
// Let's fill in the form and submit it
await page.$eval('.js-username-field', (el, payload) => el.value = payload, CREDENTIALS.username)
await page.$eval('.js-password-field', (el, payload) => el.value = payload, CREDENTIALS.password)
await page.click('button.submit')
// Wait for navigation in case there's some redirect
await page.waitForNavigation()
// We are logged in, now navigate to the page you want to get data from, i.e. account settings
await page.goto(ACCOUNT_URL)
// Wait for #user_lang select list
await page.waitForSelector('#user_lang')
// Find out what's user's selected language (there might be a better way to do this, I rarely need to do DOM manipulations)
const userLanguage = await page.$eval('#user_lang', languages => [].map.call(languages, lang => { return { lang: lang.textContent, selected: lang.selected } }).find(el => el.selected).lang)
// This scenario assumes we succeed, so I return a successful response, but you might want to return different error codes based on results
return res.status(200).json(userLanguage)
})
const server = http.createServer(app)
server.listen(8000)