Sinu Reddy
Sinu Reddy

Reputation: 49

Unable to select the dropdown value using Puppeteer Js

I am using Puppeteer JS and I'm trying to select the first element of a dropdown, please advise.

After entering the city name in the input text I need to select the first element of the dropdown list.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  const page1=await page.goto('https://www.srinu.com');
  await page.screenshot({path: 'example.png'});
  const date = '#SearchBoxContainer > div > div > div.IconBox.IconBox--autocomplete > div > div > input';
  await page.click(date);
  await page.type(date, 'China');
  await page.select('#data-text', 'Chinatown')
  // const option = (await page.$x(
   // '//*[@id="SearchBoxContainer"]/div/div/div[5]/div/div/ul/li[1]'
  // ))[0].click();

I tried two different methods, select and click, none of them worked.

Upvotes: 3

Views: 2583

Answers (2)

kalyani
kalyani

Reputation: 31

this worked for me..........

await page.select('select[id="dropdownId" or #className]', 'value')

Upvotes: 1

f-CJ
f-CJ

Reputation: 4481

There are two things missing in your code:

  1. The right selector to click on after typing 'China'
  2. Wait for the dropdown list DOM elements to be loaded after typing 'China' so it is possible to click on them.
(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  await page.goto('https://www.agoda.com');
  await page.screenshot({path: 'example.png'});
  const date = '#SearchBoxContainer > div > div > div.IconBox.IconBox--autocomplete > div > div > input';
  await page.click(date);
  await page.type(date, 'China');
  // Fix:
  const firstElement = 'ul.AutocompleteList > li.Suggestion.Suggestion__categoryName:nth-child(1) > ul.Suggestion__categoryName_container > li.Suggestion__categoryName_item:nth-child(1)';
  await page.waitForSelector(firstElement);
  await page.click(firstElement);
})();

Upvotes: 2

Related Questions