Python selenium can't click a button execute script - python

I am trying to click a button from the Linkedin public page feed
https://www.linkedin.com/company/bbc-news/
and the button is a post's toolbar button with 3 dots
here is the sample screenshot
and my code is
self.browser.execute_script("document.getElementsByClassName('feed-shared-control-menu__trigger artdeco-button artdeco-button--tertiary artdeco-button--muted artdeco-button--1 artdeco-button--circle artdeco-dropdown__trigger artdeco-dropdown__trigger--placement-bottom ember-view')[1].scrollIntoView();")
self.browser.execute_script("document.getElementsByClassName('feed-shared-control-menu__trigger artdeco-button artdeco-button--tertiary artdeco-button--muted artdeco-button--1 artdeco-button--circle artdeco-dropdown__trigger artdeco-dropdown__trigger--placement-bottom ember-view')[1].click();")
it doesn't return any errors
please kindly help me solve this issue
Thanks in advance for any help
Note: I have already tried webDriverwait , find_elements_by_class_name

The element has an id associated to it, so you can use that id to get the xpath of the element and then you can click it. Also, it is recommended to use the selenium click instead of the javascript executor click(which you are currently using).
Your code should be like:
self.browser.find_element_by_xpath("//button[#id='ember160']//li-icon").click()
If you want to use javascript executor click, then your code should be like:
element = self.browser.find_element_by_xpath("//button[#id='ember160']//li-icon")
driver.execute_script("arguments[0].click();", element)

Related

Submit button is not working in Python Selenium

I don't have experience in Selenium. I have tried a couple of things to click a submit button inside a form but nothing is working for me. Please help me out to solve this problem.
I found that the button is enabled (is_enabled()), but not displayed (is_displayed()).
I tried the following options one by one. I have added the consecutive result of that code in the comment.
z=driver.find_element_by_xpath("//input[#name='commit']")
z.click() #It is showing error, Message: element not interactable
z.send_keys(Keys.ENTER) #It is showing error, Message: element not interactable
driver.execute_script("arguments[0].click();", z) #Shows no error, but nothing happens
z.submit() #Shows no error, but nothing happens
I tried with driver.implicitly_wait(20) but no luck.
I tried with until option too but it gives error.
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[#name='commit']"))).submit() #This raises TimeoutException
The HTML code is following
input type="submit" name="commit" value="Calculate" class="btn btn-primary" autocomplete="off" data-disable-with="Calculate"
The webpage link is : https://proteins.plus/ktypdbdd9c38b7-1738-45fd-a0fb-90ea86f5dd8b
I clicked on "DoGSiteScorer Binding site detection", then "DoGSiteScorer" button. Now I want to lick the "Calculate" button which is not working.
How should I do it then?
The problem is this:
z=driver.find_element_by_xpath("//input[#name='commit']")
returns 11 elements on that page, and you can't call click() on 11 elements.
Assuming you want to click the red Calculate button, try this:
z = driver.find_element_by_xpath("(//input[#name='commit'])[2]")
z.click()

Scroll to view in filling web form error using pyAutoGUI in Python

I have this code to fill a web form:
driver.find_element_by_id("author").click() # This opens the windows file selector
pyautogui.write('John')
pyautogui.press('enter')
but if gives me an error:
selenium.common.exceptions.ElementNotInteractableException: Message: Element <select id="author" class="select2-authors-multiple select2-hidden-accessible" name="author[]"> could not be scrolled into view
how can i resolve this? i have tried some code but it did not work like:
driver.execute_script("arguments[0].scrollIntoView();", element)
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
Because you are using pyautogui try to instead of scroll, to navigate with the arrows down like this pyautogui.press("down")

How to locate the element in this?

I am new to Selenium programming and have an issue.
z=driver.find_elements_by_xpath("/html/body/div[3]/div/div[3]/div/div[2]/div/div/div[2]/div/table[1]/tbody/tr/td[2]/div/div[3]/input[1]")
text = input("Gebietsdefinition: ")
z[0].send_keys(text)
time.sleep(2)
xpath : /html/body/div[3]/div/div[3]/div/div[2]/div/div/div[2]/div/table[1]/tbody/tr/td[2]/span
id : dijit_form_Button_18
class : dijit dijitReset dijitInline SendRequest dijitButton
this is the full xpath, class & id of the button. But when I use the command,
driver.find_element_by_id("dijit_form_Button_18").click()
it executes in python without any error, but the webdriver stays the same.
NB: The button changes its class when I move the cursor over the button to "Hover" and changes to "Button ActiveFocused" when I click.
I hope somebody can shed some light into this. Thank you in advance.
Basically, you are tying to say that no error comes and click effect is also not visible.
Most probably, Selenium is clicking the element before it is clickable that is before the element is enabled to be clicked.
You can:
Introduce some delay in between using wait
Or you can use webdriverwait class and that will help
Without looking at the HTML with you, I hope that I can answer your population question. For the population question, you should import the following
from selenium import webdriver
from selenium.webdriver.common.by import By
and then you can try to populate your textbox with the following steps
element = driver.find_element(By.XPATH, "Your xpath here")
customText = "Your text here"
element.send_keys(customText)
# Gets the text that displays inside of our textbox after population
inputText = driver.find_element(By.XPATH, "Your xpath here").get_attribute('value')
if inputText.lower() != customText.lower():
raise Exception("Textbox failed to populate")
If the input tag is a button and has the following class elements
dijit dijitReset dijitInline SendRequest dijitButton
then you can use the following xpath to get your button
//input[contains(#class, 'SendRequest') and contains(#class, 'dijitButton')]
and then click it by using the following command
driver.find_element(By.XPATH, "//input[contains(#class, 'SendRequest') and contains(#class, 'dijitButton')]").click()
I hope this helps point you in the right direction.

Not able to click a button in Selenium (Booking.com)

I am programming a python scraper with help of Selenium. The first few steps are:
goes on booking.com, insert a city name, selects the first date and then tries to open the check-out calendar.
Here is where my problem occurs. I am not able to click the check-out calendar button (The important are of the website).
I tried to click every element regarding to the to check-out calendar (The elements of check-out calendar) with element.click(). I also tried the method
element = self.browser.find_element_by_xpath('(//div[contains(#class,"checkout-field")]//button[#aria-label="Open calendar"])[1]') self.browser.execute_script("arguments[0].click();", element)
It either does nothing (in case of execute.script() and click() on div elements) or it throws following exception when directly clicking the button:
Element <button class="sb-date-field__icon sb-date-field__icon-btn bk-svg-wrapper"
type="button"> is not clickable at point (367.5,316.29998779296875)
because another element <div class="sb-date-field__display"> obscures it
Here is a short code to test it:
browser = webdriver.Firefox()
browser.get("https://www.booking.com/")
wait = WebDriverWait(browser, 5)
element = wait.until(EC.presence_of_element_located((
By.XPATH, '(//div[contains(#class,"checkout-field")]//button[#aria-label="Open calendar"])[1]')))
element = wait.until(EC.element_to_be_clickable((
By.XPATH, '(//div[contains(#class,"checkout-field")]//button[#aria-label="Open calendar"])[1]')))
element.click()
I have a temporarily solution for my problem but I am not satisfied with it.
element = browser.find_element_by_xpath('(//div[contains(#class,"checkout-field")]//button[#aria-label="Open calendar"])[1]')
hov = ActionChains(browser).move_to_element(element)
hov.click().perform()
This will open the calendar by hovering over the object and clicking it. This strangely opens the calendar.
The methods mentioned above still don't work.
Define clicka as an xpath. Now use executescript to click the element.
driver.execute_script("arguments[0].click();", clicka)
I'm not 100% sure that I got everything you posted, because the layout is a bit messy.
However, I tried to test the issue with both Selenium Java and Firefox Scratchpad (a Web Developer tool that allows to run JavaScript scripts) and it worked perfectly - the button was clickable on both of them.
If you're interested in further testing using this tool, this is the code I've used:
In JavaScript:
function getElementByXpath(path) {
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
}
var myElement = getElementByXpath('(//div[contains(#class,"checkout-field")]//button[#aria-label="Open calendar"])[1]')
myElement.click()
and in Java:
FirefoxDriver driver = new FirefoxDriver();
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.navigate().to("https://www.booking.com");
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[contains(#class,'checkout-field')]//button[#aria-label='Open calendar'])[1]")));
driver.findElement(By.xpath("(//div[contains(#class,'checkout-field')]//button[#aria-label='Open calendar'])[1]")).click();
System.out.println("success");
if your are having the control check out button on all the web site managing with explicit wait required lots of codding you can use implicit wait below is in the java.
System.setProperty("webdriver.chrome.driver",
"G:\\TopsAssignment\\SampleJavaExample\\lib\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

Python+Selenium, can't click the 'button' wrapped by span

I am new to selenium here. I am trying to use selenium to click a 'more' button to expand the review section everytime after refreshing the page.
The website is TripAdvisor. The logic of more button is, as long as you click on the first more button, it will automatically expand all the review sections for you. In other words, you just need to click on the first 'more' button.
All buttons have a similar class name. An example is like taLnk.hvrIE6.tr415411081.moreLink.ulBlueLinks. Only the numbers part changes everytime.
The full element look like this:
<span class="taLnk hvrIE6 tr413756996 moreLink ulBlueLinks" onclick=" var options = {
flow: 'CORE_COMBINED',
pid: 39415,
onSuccess: function() { ta.util.cookie.setPIDCookie(2247); ta.call('ta.servlet.Reviews.expandReviews', {type: 'dummy'}, ta.id('review_413756996'), 'review_413756996', '1', 2247);; window.location.hash = 'review_413756996'; }
};
ta.call('ta.registration.RegOverlay.show', {type: 'dummy'}, ta.id('review_413756996'), options);
return false;
">
More </span>
I have tried several ways to get the button click. But since it is an onclick event wrapped by span, I can't successfully get it clicked.
My last version looks like this:
driver = webdriver.Firefox()
driver.get(newurl)
page_source = driver.page_source
soup = BeautifulSoup(page_source)
moreID = soup.find("span", class_=re.compile(r'.*\bmoreLink\b.*'))['class']
moreID = '.'.join(moreID[0:(len(moreID)+1)])
moreButton = 'span.' + moreID
button = driver.find_element_by_css_selector(moreButton)
button.click()
time.sleep(10)
However, I keep getting the error message like this:
WebDriverException: Message: Element is not clickable at point (318.5,
7.100006103515625). Other element would receive the click....
Can you advise me on how to fix the problem? Any help will be appreciated!
WebDriverException: Message: Element is not clickable at point (318.5, 7.100006103515625). Other element would receive the click....
This error to be occur when element is not in the view port and selenium couldn't click due to some other overlay element on it. In this case you should try one of these following solution :-
You can try using ActionChains to reach that element before click as below :-
from selenium.webdriver.common.action_chains import ActionChains
button = driver.find_element_by_css_selector(moreButton)
ActionChains(button).move_to_element(element).click().perform()
You can try using execute_script() to reach that element before click as :-
driver.execute_script("arguments[0].scrollIntoView(true)", button)
button.click()
You can try using JavaScript::click() with execute_script() but this JavaScript::click() defeats the purpose of the test. First because it doesn't generate all the events like a real click (focus, blur, mousedown, mouseup...) and second because it doesn't guarantee that a real user can interact with the element. But to get rid from this issues you can consider it as an alternate solution.
driver.execute_script("arguments[0].click()", button)
Note:- Before using these options make sure you're trying to interact with correct element using with correct locator, otherwise WebElement.click() would work well after wait until element visible and clickable using WebDriverWait.
Try using an ActionChains:
from selenium.webdriver.common.action_chains import ActionChains
# Your existing code here
# Minus the `button.click()` line
ActionChains(driver).move_to_element(button).cli‌​ck().perform()
I have used this technique when I need to click on a <div> or a <span> element, rather than an actual button or link.

Categories

Resources