简体   繁体   中英

How to click on element from select list with puppeteer

I'm trying to create a automation on some website with puppeteer and I have a trouble with that when I try to click on element inside select list.

All I found about that after some google search is to select an item but only when the list is inside "select" element. My problem is that the HTML I try to automate is inside a 'div':

<div class="dropdown open dropdown--gray">
  <div class="dropdown__header">
     <div class="dropdown__field">other</div>
     <div class="dropdown__opener">
        <span class="icon icon-chevron-down"></span>
     </div>
  </div>
  <div class="dropdown__list">
    <div class="dropdown__list-item selected">other</div>
    <div class="dropdown__list-item">.org</div>
    <div class="dropdown__list-item">.co.uk</div>
    <div class="dropdown__list-item">.net</div>
    <div class="dropdown__list-item">.gov</div>
    <div class="dropdown__list-item">.de</div>
    <div class="dropdown__list-item">.fr</div>
    <div class="dropdown__list-item">.nl</div>
    <div class="dropdown__list-item">.com</div>
    <div class="dropdown__list-item">.be</div>
    <div class="dropdown__list-item">.jpg</div>
  </div>
</div>

I have tried this:

await page.click('div.dropdown__field');
const elementHandle4=await page.$$("div.dropdown__list-item");
await elementHandle4[8].click();

but actually its not click on the element. When I open manually the list after this code ran, I see that its scrolled down the scroller of the list but not clicked on the element.

Thanks

Try something like this:

await page.click('.dropdown__field');
await page.click('.dropdown__list > div:nth-child(8)');

UPDATE:

It looks like the problem in the viewport because it works correctly and selects the '.nl' option without any scrolling with the following script:

(async () =>  {
    const browser = await puppeteer.launch({ 
        headless: false,
        defaultViewport: null,
    });
    const page = await browser.newPage();
    await page.goto('https://userinyerface.com/game.html');
    await page.click('.dropdown__field');
    await page.click('.dropdown__list > div:nth-child(8)');
})();

But it will not work if I remove the defaultViewport: null property

I guess you need to see that element to trigger click event. First, you must scroll to the position of the element to see the element then trigger the click event.


It works for me

const ListItemIndex = 10, ListItem = document.querySelector(`.dropdown__list > div:nth-child(${ListItemIndex})`);
document.querySelector(".dropdown__list").scroll({ behavior: 'smooth', top: ListItem.offsetTop });
ListItem.click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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