如何单击伪娘中具有特定内容的链接? [英] How to click on a link that has a certain content in puppeteer?
问题描述
如果我的页面上有一些内容,例如:
If I have some content in my page such as:
<a>Hi!</a>
如何使用Google的Puppeteer自动点击该元素?
How can I use Google's Puppeteer to automate the clicking of that element?
我需要能够仅根据其内容而不是id,class或属性来选择它.
I need to be able to select it based on its contents alone, not id, class or attribute.
是否可以利用像$('a:contains("Hi!")')
这样的东西来选择此元素?
Is there something like $('a:contains("Hi!")')
that I can leverage to select this element?
我该如何使用 https://github.com/GoogleChrome/puppeteer
谢谢
推荐答案
首先,我们必须按文本查找元素.
First, we have to find element by text.
/**
* findElemByText - Find an Element By Text
*
* @param {String} str case-insensitive string to search
* @param {String} selector = '*' selector to search
* @param {String} leaf = 'outerHTML' leaf of the element
* @return {Array} array of elements
*/
function findElemByText({str, selector = '*', leaf = 'outerHTML'}){
// generate regex from string
const regex = new RegExp(str, 'gmi');
// search the element for specific word
const matchOuterHTML = e => (regex.test(e[leaf]))
// array of elements
const elementArray = [...document.querySelectorAll(selector)];
// return filtered element list
return elementArray.filter(matchOuterHTML)
}
// usage
// findElemByText({str: 'Example', leaf: 'innerHTML', selector: 'title'});
// findElemByText({str: 'Example', selector: 'h1'});
// findElemByText({str: 'Example'});
将其与人偶脚本保存在同一文件夹中,并将其命名为script.js
.
Save it in same folder as your puppeteer script, name it script.js
.
现在,我们可以在我们的操纵script脚本中使用它.我们可以使用ElementHandle,但是为了便于理解,我将使用puppeteer随附的.evaluate()
函数.
Now, we can use this in our puppeteer script. We can use ElementHandle, but for simplicity of understanding, I'll use .evaluate()
function provided with puppeteer.
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://example.com');
// expose the function
await page.addScriptTag({path: 'script.js'});
// Find Element by Text and Click it
await page.evaluate(() => {
// click the first element
return findElemByText({str: 'More'})[0].click();
});
// Wait for navigation, Take Screenshot, Do other stuff
await page.screenshot({path: 'screenshot.png'});
await browser.close();
})();
请勿复制粘贴上面的代码,尝试理解它并自己键入.如果上面的代码失败,请尝试查找失败的原因.
Do not copy paste the code above, try to understand it and type them yourself. If the code above fails, try to find why it's failing.
这篇关于如何单击伪娘中具有特定内容的链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!