我刚刚开始学习 Node 和 Puppeteer,所以请原谅我是一个菜鸟..
我的 index.html 页面上有一个简单的表单,我希望它从运行 Puppeteer 的 NODE 服务器上的函数返回 Instagram 配置文件的图像。在下面的代码中有一个 Index.HTML 文件和一个 Index.JS 文件,在 Index.HTML 文件中,当单击按钮时,我只想使用传入用户名的 AJAX 请求调用服务器并运行该函数在服务器上,将结果返回到 HTML 文件并将响应文本放入 .images div(我可以拆分结果并稍后渲染 img 标签)
我有几个问题:
1:我在 VSC 中使用 liveserver 插件运行 server.js,它在 http://127.0.0.1:5500/12_Puppeteer/12-scraping-instagram/index.js
上运行文件现在是终点吗?那么我如何将用户名传递给服务器功能..在标题或网址中?你能给我看看吗?
2:在我的 Index.HTML 文件中的 AJAX 请求中,请求需要什么才能将用户名传递给服务器 scrapeImages(username)
函数并取回返回的内容?
.
这是我在 index.html 文件中尝试过的:
<body>
<form>
Username: <input type="text" id="username">
<button id="clickMe" type="button" value="clickme" onclick="scrape(username.value);">
Scrape Account Images</button>
</form>
<div class="images">
</div>
</body>
<script>
function scrape() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.querySelector(".images").innerHTML = this.responseText;
}
};
xhttp.open("GET", "http://127.0.0.1:5500/12_Puppeteer/12-scraping-instagram/index.js", true);
xhttp.send();
}
</script>
这是我的 index.js 文件(在我使用我的用户名/密码进行调试时工作):
const puppeteer = require("puppeteer");
const fs = require('fs');
async function scrapeImages (username) {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.goto('https://www.instagram.com/accounts/login/')
await page.type('[name=username]','xxxxxx@gmail.com')
await page.type('[name=password]','xxxxxx')
await page.click('[type=submit]')
await page.goto(`https://www.instagram.com/${username}`);
await page.waitForSelector('img', {
visible: true,
})
const data = await page.evaluate( () => {
const images = document.querySelectorAll('img');
const urls = Array.from(images).map(v => v.src + '||');
return urls;
} );
fs.writeFileSync('./myData2.txt', data);
return data;
}
最佳答案
您必须设置一个节点服务器,例如 express 或其他任何服务器,然后通过 POST/GET 方法传递用户名并使用 node/express 捕获用户名。然后你可以用它来运行 puppeteer。
例如,您的 node.js/express 服务器在端口 8888 上运行。 你的 HTML 应该是这样的:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
Username: <input type="text" name="username" id="username">
<button id="clickMe" type="button" value="clickme" onclick="getImages(this.form.username.value)">
Scrape Account Images</button>
</form>
<div id="scrapedimages"></div>
<script>
let imgArray
const getImages = (username) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.querySelector('#scrapedimages').innerHTML = ''
imgArray = JSON.parse(this.responseText)
if ( imgArray.images.length > 0 ) {
imgArray.images.split(',').forEach( function (source) {
var image = document.createElement('img')
image.src = source
document.querySelector('#scrapedimages').appendChild(image)
})
}
}
};
xhttp.open('GET', 'http://127.0.0.1:8888/instascraper/user/' + username, true);
xhttp.send();
}
</script>
</body>
</html>
然后在你的 node.js/server 中你的脚本将是这样的
const puppeteer = require('puppeteer')
const fs = require('fs-extra')
const express = require('express')
const app = express()
const port = 8888
const username = 'usernameInstaGram'
const password = 'passwordInstaGram'
;(async () => {
app.get('/instascraper/user/:userID', async (request, response) => {
const profile = request.params.userID
const content = await scrapeImages (profile)
response.set({
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': true,
'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Content-Type': 'text/plain'
})
response.send(content)
})
app.listen(port, () => {
console.log(`Instascraper server listening on port ${port}!`)
})
const scrapeImages = async profile => {
const browser = await puppeteer.launch()
const [page] = await browser.pages()
await page.goto('https://www.instagram.com/accounts/login/', {waitUntil: 'networkidle0', timeout: 0})
await page.waitForSelector('[name=username]', {timeout: 0})
await page.type('[name=username]', username)
await page.waitForSelector('[name=password]', {timeout: 0})
await page.type('[name=password]',password)
await Promise.all([
page.waitForNavigation(),
page.click('[type=submit]')
])
await page.waitForSelector('input[placeholder="Search"]', {timeout: 0})
await page.goto(`https://www.instagram.com/${profile}`, {waitUntil: 'networkidle0', timeout: 0})
await page.waitForSelector('body section > main > div > header ~ div ~ div > article a[href] img[srcset]', {visible:true, timeout: 0})
const data = await page.evaluate( () => {
const images = document.querySelectorAll('body section > main > div > header ~ div ~ div > article a[href] img[srcset]')
const urls = Array.from(images).map(img => img.src )
return urls;
})
await browser.close()
return `{
"images" : "${data}"
}`
}
})()
关于javascript - 如何在 NODE 服务器上使用 Puppeteer 并在前端 HTML 页面上获取结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59472110/