Home > database >  click on first search auto suggestion on website via VBA macro with selenium
click on first search auto suggestion on website via VBA macro with selenium

Time:08-02

I would like to know how I could program in VBA using Selenium to click/choose on website the first autosuggestion, for example as you can see in the screenshot from amazon.esamazon.es

Do you have any suggestions?

Tom

CodePudding user response:

I used Firefox to get the xPath property of that suggestion made by the web page. To quickly compare, I copied and pasted, one at a time, the xPath of the first 3 suggestions shown:

/html/body/div[1]/header/div/div[2]/div/div[2]/div[1]/div/div[1]/span[1]
/html/body/div[1]/header/div/div[2]/div/div[2]/div[2]/div/div[1]/span[1]
/html/body/div[1]/header/div/div[2]/div/div[2]/div[3]/div/div[1]/span[1]

So, for the first item, just use the first xPath. If you want to select, for example, the second, just vary the index of the sixth DIV, as we can see in the samples above. Assuming you already have part of the code that navigates to the page, use this, adapting the name of the WebDriver:

objSeleniumDriver.FindElementByXPath("/html/body/div[1]/header/div/div[2]/div/div[2]/div[1]/div/div[1]/span[1]"). click

CodePudding user response:

Since your situation is replicable I managed to test this two (2) approaches to your situation. I'll just remind you that is always good to show us some code you've tried in your question, so it does not feel like we are helping you from scratch, also try not to rely on images to show us your situation, unless is something that does not change much «like in this case, Amazon.es page». That reminded, let's go to the good part:

1) Advanced 1:
    a. Spaces in class are change for dots (if there is any)
    b. Requires to understand tag's meaning (a tag is like an object)
    'Example
        'Clicking first element under tag ("div" alone is a tag)
         Selenium.FindElementByCss("div.autocomplete-results-container > div").Click
2) Advanced 2:
    a. Requires to understand what ":nth-child" (CSS selector) is
     'Example:
         'Clicking first child of "div" (Everything inside "div" is a child - starts in 1)
          Selenium.FindElementByCss("div.autocomplete-results-container > div:nth-child(1)").Click
  • Related