Selecting options in dropdown Selenium ChromeDriver in VBA - excel

I'm trying to select the options of a dropdown list in Chrome using VBA and Selenium.
I manage to open the dropdown but not navigate the options. Can anyone help?
This is the VBA code:
Sub FormChrome()
'Import Selenium Library
Dim driver As New ChromeDriver
'Navigate to the website
driver.Get "https://fremtindservice.no/privat/bompengekalkulator/"
' Wait for page to load
driver.Wait (10)
driver.Window.Maximize
' Locate the first input element using its class and set its value
driver.FindElementByCss("label[for='origin'] ~ div .pac-target-input").SendKeys "Oslo"
' Locate the second input element using its class and set its value
driver.FindElementByCss("label[for='destination'] ~ div .pac-target-input").SendKeys "Rakkestad"
driver.FindElementByCss("label[for='via'] ~ div .pac-target-input").SendKeys ""
'driver.FindElementByCss("div.dropdown.v-select.toll-road-calculator__vehicle-type.single.searchable").Click
' Import Selenium Library
' Wait for page to load
driver.Wait (10)
' Locate the dropdown element using its class and click to open it
driver.FindElementByCss("div.dropdown.v-select.toll-road-calculator__vehicle-type.single.searchable").Click
' Wait for page to load
driver.Wait (10)
' Locate the desired option using its position in the dropdown and click to select it
driver.FindElementByCss("div.vs__dropdown-menu div.vs__dropdown-item:nth-child(3)").Click
End Sub
Here is the HTML code for the Dropdown:
Biltype
Personbil
× Loading...
As a default it says Personbil. I want that text to be the third option in the dropdownlist which is "Lastebil 3.5 tonn (Euro V og eldre)"

Do you use Visual Basic or .net C# ? As far as I know, there is not VB bindings of Selenium.
Re anser, there is special function for select list(dropbox). For #:
yourSelectList=driver.FindElement(By.Id("select-demo"));
SelectElement dropDown = new SelectElement(yourSelectList);
and then you have 3 alternative to choose options:
dropDown.SelectByText("Four");
dropDown.SelectByValue("two");
dropDown.SelectByIndex(3);
for more details you can click here

Related

Excel VBA using Selenium - click on list element to change focus

I'm trying to scape data from a website via Excel VBA. I have a web page which has different data depending on a button selection, but the button sits withing a ul list. I can find the element by class using:
.FindElementByClass("shared-filter-button-list_navItem__ZiG2J")
But I can seem to work out how to switch the focus between 'This season' and 'All time' to change to displayed data on the page. Any ideas would be gratefully received. The html is:
<ul class="shared-filter-button-list_navContainer__3hJmS"><li class="shared-filter-button-list_navItem__ZiG2J is-active"><button class="tag-button_btn__1B2dI tag-button__purple__3SyTF shared-filter-button_wrap__3OgbA is-active" value="This season" type="button">This season</button></li><li class="shared-filter-button-list_navItem__ZiG2J"><button class="tag-button_btn__1B2dI tag-button__purple__3SyTF shared-filter-button_wrap__3OgbA " value="All time" type="button">All time</button></li></ul>
It would help to see the page, but if you just want to click the "this season" or "all time" button, just find the buttons inside the list you already have and click one?
update
I misread the provided HTML (its all in one line) and thought that shared-filter-button-list_navItem__ZiG2J was the container ul not the list items, and also that selenium uses 1-based indexes not 0-based.
The code below finds all buttons that match the query and prints their index and text to the debug window.
Private Driver As Selenium.ChromeDriver
Sub Main()
Set Driver = New Selenium.ChromeDriver
Driver.Get "https://www.euroleaguebasketball.net/eurocup/players/lukas-meisner/011187/"
Dim List As Selenium.WebElements
' get a list of button that are children of li with specified class name
Set List = Driver.FindElementsByXPath("//li[contains(#class, 'shared-filter-button-list_navItem__ZiG2J')]/button", 0, 5000)
If List Is Nothing Then
Debug.Print "failed to get list"
Exit Sub
End If
For Index = 1 To List.Count
Debug.Print Index & " -> " & List(Index).Text
Next Index
End Sub
Expected result from this code is:
1 -> This season
2 -> All time
3 -> Regular Season
If you wanted to click the This season button
List(1).Click

GetAttribute in Selenium VBA for style

I am working on selenium in VBA and I have stored a variable"post" to store all the occurrences of a specific element like that
Dim post As Object
Set post = .FindElementsByCss("#DetailSection1")
Dim i As Long
For i = 1 To post.Count
Debug.Print post.Item(i).getAttribute("style")
Next i
I need to extract the style value from the elements
<div id="DetailSection1" style="z-index:3;clip:rect(0px,746px,32px,0px);top:228px;left:0px;width:746px;height:32px;">
</div>
Also I need to print in the immediate window the innerHTML and when I used getAttribute("innerHTML"), it doesn't work for me
Any ideas
getAttribute("style") should work but you have to induce a waiter for the element to be present/visible within the HTML DOM.
Debug.Print post.Item(i).getAttribute("style")
Precisely, to extract value of the style attributes from the elements you can use the getCssValue() method as follows:
Debug.Print post.Item(i).getCssValue("z-index")
Debug.Print post.Item(i).getCssValue("top")
Debug.Print post.Item(i).getCssValue("left")
Debug.Print post.Item(i).getCssValue("width")
Debug.Print post.Item(i).getCssValue("height")
getAttribute("innerHTML")
get_attribute("innerHTML") can be used to read the innerHTML or the text within any node / WebElement
You can find a detailed discussion in Difference between text and innerHTML using Selenium
References
You can find a couple of relevant discussions in:
How to get child property value of a element property using selenium webdriver, NUnit and C#
How can I verify text is bold using selenium on an angular website with C#

Activate selenium bot window in excel VBA

I am trying to make the window of the selenium bot activated ...
First I declared this line
Dim mainWin As selenium.Window
then after the Get line
.Get "https://www.kuwaitcourts.gov.kw/searchPages/searchCases.jsp"
I put this line that sets the window
Set mainWin = .Window
and before a message box I would like to activate the bot window so I used these lines
mainWin.Activate
MsgBox "Click OK After Entering Captcha", 64
There is no problem at the start of the loop as the bot window is already active but as for the second loop I didn't get the bot window activated
Any idea how to overcome this point and make the selenium bot window active when needed to be active
Thanks advanced for help
Use javascript to return focus? For having window at front
bot.ExecuteScript "window.focus();"
Ways of pausing for input:
inputbox:
Why not use an inputBox (set to number type) to capture entry ? Below is pseudo code (assuming captcha is in an iframe which needs to be switched to.
Dim captchaBox As Object, captcha As Long
.SwitchToFrame (.FindElementById("someId")) '<==some identifier for iframe if present
Set captchaBox = .FindElementByCss("#txtCaptia")
' Accept Number from the user
captcha = Application.InputBox("Please enter 4 digit captcha:", "Captcha", , , , , , 1)
captchaBox.Value = captcha
'.SwitchToDefaultContent ''<back to main if in iframe and is required even after submit.
DoEvents and loop until desired length:
Code
Dim submitButton As Object
Set submitButton = .FindElementsByCss("#cmdSubmit")
Do
DoEvents
Loop Until submitButtons.count = 0
Or
Dim captcha As Object
Set captcha = .FindElementsByCss("#txtCaptcha")
Do
DoEvents
Loop Until len(captcha.value) = 4

Selenium VBA runs fine with step F8 but skips a line when running in full F5 [duplicate]

This question already has answers here:
Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click
(9 answers)
Element MyElement is not clickable at point (x, y)... Other element would receive the click
(5 answers)
Closed 4 years ago.
I searched all over the internet and in this forum and can't find the answer. Below code is used to upload file to a wordpress website. When I use F8 to step through it, it works fine. However, when run the full code, after the upload using XPath ("//input[starts-with(id, 'htm15_')]").SendKeys (ws.Cells(1.4)), the macro seems to skip the next line which is to click on a button (Insert file URL) and the browser stucks on this uploading page and will not load the next page where the Publish button appears. At this point, an error came out and stated couldn't find the element Publish.
I try different things, adding global ImplicitWait, adding timeouts for the above mentioned lines of code and to no avail. It seems that after uploading the file, the macro just doesn't click the button (skips that line of code) and therefore couldn't find the Publish button in the next line. The problem lines of code have been indicated by 2 asterisks. Appreciate any help.
Public Sub UploadPost()
Dim ws As Worksheet
Dim filename As String
Dim wb As Workbook
Dim D As WebDriver
Dim Path As String
Dim i As Integer
Set ws = ThisWorkbook.Worksheets("Data")
Set D = New ChromeDriver
Const URL = "https://www.myweb.com/login/"
'To login to website
With D
.Timeouts.ImplicitWait = 10000 'global implicit wait 5 seconds than default 3 seconds
.Start "Chrome"
.Window.Maximize
.Get URL
.FindElementById("user_login").SendKeys("id").Click
.FindElementById("user_pass").SendKeys("pw").Click
.FindElementByName("submit").Click
End With
'Upload daily file to Download Monitor and get file ID
ws.Range("H2:H9").Clear
D.FindElementById("menu-posts-dlm_download").Click 'Click Download on left menu
For i = 2 To 9
With D
.FindElementByClass("page-title-action").Click 'Click Add New
.FindElementById("title").SendKeys(ws.Cells(i, 2)).Click 'Type title copy from spreadsheet
.FindElementById("_members_only").Click 'Click members only category
.FindElementById(ws.Cells(i, 3)).Click '17-china, 21-HK, 25-NAS, 10-NYSE
.FindElementByLinkText("Add file").Click 'Add File
.FindElementByXPath("//input[starts-with(#id,'dp')]").Clear 'Select the correct date
.FindElementByXPath("//input[starts-with(#id,'dp')]").SendKeys (ws.Cells(i, 9))
.FindElementByLinkText("Upload file").Click
.FindElementByLinkText("Upload Files").Click
.FindElementByXPath("//input[starts-with(#id,'html5_')]").SendKeys (ws.Cells(i, 4)) 'upload file using path from spreadsheet
**.FindElementByXPath("//*[#id='__wp-uploader-id-0']/div[5]/div/div[2]/button").Click 'Click save Insert file URL
.FindElementById("publish").Click**
ws.Cells(i, 8) = D.FindElementByXPath("//*[#id='dlm-info-url']").Value
End With
Next i

Pulling Excel data across multiple firefox pages in Python, Selenium

Goal: Take a list of First and Last names from Excel, and put them into an online registration form, using multiple firefox pages, with only one first name and one last name per page.
Tasks:
Open firefox page
Fill in "First Name" text box with Excel, cell 'A2'="Bob"
Fill in "Last Name" text box with Excel, cell 'B2'="Apple"
Click 'Submit'. -- End of Registration 1 --
Open a new firefox page
Fill in "First Name" text box with Excel, cell 'A3'="Linda"
Fill in "Last Name" text box with Excel, cell 'B3'= "Orange"
Click 'Submit'.
for x in range(2):
from selenium import webdriver
browser=webdriver.Firefox()
browser.get('The Website')
import openpyxl
wb=openpyxl.load_workbook('Names.xlsx')
sheet=wb.get_sheet_by_name('Full Names')
tuple(sheet['A2':'B3'])
#I'm guessing about this next part:
for rowOfCellObjects in sheet['A2':'B3']:
for cellObj in rowOfCellObjects:
browser.find_element_by_id('first_name').send_keys(????)
browser.find_element_by_id('last_name').send_keys(????)
Using Python 3.6.2. Excel 2016. Windows 10 x64. Selenium.
Please dumb it down in the answers, I'm very new to coding :). Thanks!!
This is my usual format:
import pandas as pd
from selenium import webdriver
driver = webdriver.Firefox()
headers = ['first_name', 'last_name']
data = pd.read_csv('Names.csv', names=headers) #Youll want to change the .xlsx to .csv
depth = len(data['first_names']) #this finds how deep the columns are
url = "www.website.com"
driver.get(url) #opens browser
for i in range (0,depth):
driver.find_element_by_xpath('first_name').send_keys(data['first_name'][i])
driver.find_element_by_xpath('last_name').send_keys(data['last_name'][i])
driver.find_element_by_xpath('submit').click()
Also note that in find_element_by_xpath, the format is:
driver.find_element_by_xpath('//input[#name = "first_name"]')
or similar. Youll need to ctl+i or right click-->Inspect to find the xpath.
'input' is the main tag name, and 'name' will be whatever element of 'input' has the "first_name" string literally embedded.

Resources