您必须设置一个节点服务器,例如express或其他任何东西,然后通过POST / GET方法传递用户名,并使用node / express捕获用户名。然后,您可以使用它来运行木偶。
我才刚刚开始学习Node和Puppeteer,所以请原谅自己是菜鸟。。
我在index.html页面上有一个简单的表单,我希望它从运行Puppeteer的NODE服务器上的函数返回Instagram个人资料的图像。在下面的代码中,在Index.HTML文件中有一个Index.HTML文件和一个Index.JS文件,当单击按钮时,我只想通过传入用户名并运行该功能的AJAX请求来调用服务器。在服务器上,将结果返回到HTML文件,并将响应文本放入.images div(我可以拆分结果并稍后渲染img标签)
我有几个问题:
1:我正在VSC中使用liveserver插件运行server.js,并且它正在http://127.0.0.1:5500/12_Puppeteer/12-scraping-instagram/index.js
上运行文件,现在是端点吗?然后,如何将用户名传递给服务器函数。在标题中还是在url中?你可以告诉我吗?
2:在我的AJAX请求中的Index.HTML文件中,将用户名传递给服务器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]','[email protected]') 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; }
我才刚刚开始学习Node和Puppeteer,所以请原谅自己是菜鸟。。我在index.html页面上有一个简单的表单,我希望它从...返回Instagram个人资料的图片...] >
您必须设置一个节点服务器,例如express或其他任何东西,然后通过POST / GET方法传递用户名,并使用node / express捕获用户名。然后,您可以使用它来运行木偶。
例如,您的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}"
}`
}
})()
您必须设置一个节点服务器,例如express或其他任何东西,然后通过POST / GET方法传递用户名,并使用node / express捕获用户名。然后,您可以使用它来运行木偶。