简体   繁体   English

如何在 ul / puppeteer 中点击 li

[英]How to click li in ul / puppeteer

I'm new to the puppeteer.我是木偶师的新手。 I wonder, how to click li elements in puppeteer?我想知道,如何在 puppeteer 中点击 li 元素? I do this code.我做这个代码。 but it doesn't work.但它不起作用。

 await page.click('#currentSearchByTop') await page.click('#ul.sl_general:last-child(2)')

enter image description here

your first click's CSS selector is correct, but the one you are using in the 2nd is not:您第一次点击的 CSS 选择器是正确的,但您在第二次使用的选择器不是:

await page.click('#ul.sl_general:last-child(2)') // invalid and mismatched selector
  • do not put # in front of the ul , it is valid in itself不要把#放在ul前面,它本身是有效的

  • the <ul> 's id is "sl_general" so you should put a # in front of it (and not a . ). <ul>的 id 是“sl_general”,所以你应该在它前面放一个# (而不是. )。

  • also :last-child(2) is not a valid pseudo-class in CSS, you wanted to use :nth-last-child(2) or simply :last-child :last-child(2)也不是 CSS 中的有效伪类,您想使用:nth-last-child(2)或简单地使用:last-child

await page.click('ul#sl_general:nth-last-child(2)') // valid selector

I recommend reading more about selectors on MDN .我建议在MDN上阅读有关选择器的更多信息。

to answer in general you can compose your selector like this to click specific li within ul element, by using its index:一般来说,您可以像这样编写选择器来单击 ul 元素中的特定 li,方法是使用它的索引:

const lis = await page.$$('ul#sl_general li') // all <li> element handles within the ul
await lis[0].click()
// OR
await lis[2].click()

did you know?你可知道? if you right-click on an element in Chrome DevTools "Elements" tab and you can select "Copy": there you are able to copy the exact CSS selector or XPath of an element.如果您右键单击 Chrome DevTools“元素”选项卡中的元素,您可以 select“复制”:您可以复制确切的 CSS 选择器或元素的 ZB6454D498635710A189184A13BE。 after that, you can switch to the "Console" tab and with the Chrome API you are able to test the selector's content, so you can prepare it for your puppeteer script.之后,您可以切换到“控制台”选项卡,使用 Chrome API 可以测试选择器的内容,以便为您的 puppeteer 脚本准备它。 Eg: $("ul#sl_general:nth-last-child(2)").href should show the link that you expected to click on, otherwise you need to change on the access, or you need to check if there are more elements with the same selector, etc. this may help to find more appropriate selectors.例如: $("ul#sl_general:nth-last-child(2)").href应该显示你希望点击的链接,否则你需要更改访问,或者你需要检查是否还有更多具有相同选择器的元素等。这可能有助于找到更合适的选择器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM