AGr*_*ush 2 javascript ajax puppeteer
我刚刚开始学习 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>
Run Code Online (Sandbox Code Playgroud)
这是我的 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;
}
Run Code Online (Sandbox Code Playgroud)
您必须设置一个节点服务器,例如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>
Run Code Online (Sandbox Code Playgroud)
然后在你的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}"
}`
}
})()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4418 次 |
| 最近记录: |