How to find element by its class Selenium? - python

I'm trying to click Log In button on Facebook Page. I'm trying to locate the button by class_name, but it returns an error.
html:
python:
submit = browser.find_element_by_class_name("a8c37x1j ni8dbmo4 stjgntxs l9j0dhe7 ltmttdrg g0qnabr5").text("Log In")

The space in the class name is like a seperator for the classes in css, what means that you look for many classes at once, so it wont work. Try it like this:
submit = browser.find_element_by_class_name("a8c37x1j")
And when you want to click the button later on, you have to remove .text, because it just gives you the text of the button, but not the element. In order to click, just do this:
submit.click()

You can chain it with css selectors.
Example
from selenium import webdriver
html = '''<span class="a8c37x1j ni8dbmo4 stjgntxs l9j0dhe7 ltmttdrg g0qnabr5">Log In</span>'''
driver = webdriver.Chrome(executable_path=r'C:\Program Files\ChromeDriver\chromedriver.exe')
driver.get("data:text/html;charset=utf-8,{0}".format(html))
driver.find_element_by_css_selector("span.a8c37x1j.ni8dbmo4.stjgntxs.l9j0dhe7.ltmttdrg.g0qnabr5")

Related

How to click a button using selenium and draw on a canvas in python?

so I am trying to automate a program that would log in to a google account I created, go to this canvas website, and draw a circle,
(Circle just as a placeholder because im trying to make it draw some cool stuff like a car, just to test if it will work first.) But the main issue is when you first go into the website, there is a pop up that displays and that pop up has 2 options, "learn more" and "Get started". I tried to make selenium click on the "Get started" using driver.find_element_by_id('Get-started').click but it does not seem to work, I also tried to use CSS selector but that does not seem to work either. So, I'm stuck on this. Any advice or help to click the get started button? (Feel free to also give me advice on how to draw in the canvas as well!)
Here's the HTML:
<paper-button id="get-started" dialog-confirm="" class="primary" aria-label="Get started" role="button" tabindex="0" animated="" elevation="0" aria-disabled="false">
Get started
</paper-button>
here's the code:
from selenium import webdriver
import time
from PrivateInfo import*
driver = webdriver.Chrome(r"D:\chromeDriver\chromedriver.exe")
link = "https://www.google.com/"
driver.get(link)
def linkText(element):
button = driver.find_element_by_link_text(element)
button.click()
def byClass(className):
button2 = driver.find_element_by_class_name(className)
button2.click()
def type(text, elements):
input = driver.find_elements_by_name(elements)
for element in input:
driver.implicitly_wait(2)
element.send_keys(text)
linkText("Sign in")
type(email, "identifier")
byClass("VfPpkd-vQzf8d")
type(pw, "password")
driver.find_element_by_id("passwordNext").click()
time.sleep(1)
driver.get("https://canvas.apps.chrome/")
driver.implicitly_wait(3)
driver.find_element_by_css_selector('paper-button[id="get-started"]').click()
edit: I also tried this
getStart = driver.find_elements_by_css_selector('paper-button[id="get-started"]')
for start in getStart:
start.click()
it doesn't give me any errors but it does not do anything.
Ah yeah, forgot to mention but im new to using selenium.
The content of the popup is nested inside shadowRoots.
More on ShadowRoot here:
The ShadowRoot interface of the Shadow DOM API is the root node of a
DOM subtree that is rendered separately from a document's main DOM
tree.
To be able to control the element you will need to switch between DOMs. Here's how:
drawing_app_el = driver.execute_script("return arguments[0].shadowRoot", driver.find_element(By.CSS_SELECTOR, 'drawing-app'))
This code will retrieve the drawing_app first and then return the content of the shadowRoot.
To have access to the button getStarted, here's how:
# Get the shadowRoot of drawing-app
drawing_app_el = driver.execute_script("return arguments[0].shadowRoot", driver.find_element(By.CSS_SELECTOR, 'drawing-app'))
# Get the shadowRoot of welcome-dialog within drawing_app
welcome_dialog_el = driver.execute_script("return arguments[0].shadowRoot", drawing_app_el.find_element(By.CSS_SELECTOR, 'welcome-dialog'))
# Get the paper-dialog from welcome_dialog
paper_dialog_el = welcome_dialog_el.find_element(By.CSS_SELECTOR, 'paper-dialog')
# Finally, retrieve the getStarted button
get_started_button = paper_dialog_el.find_element(By.CSS_SELECTOR, '#get-started')
get_started_button.click()

Using selenium to click a button

For clicking a button with the following HTML code:
All Notes
I have tried multiple ways to click/ access this button but to no success, for example:
all_notes = wait.until(EC.presence_of_element_located((By.XPATH, "//a[#href='javascript:submitPage('V','All Notes','');']"))).click()
all_notes = wait.until(EC.presence_of_element_located((By.XPATH, "//href[#type='class' and #value='View All']"))).click()
I am not really sure what the issue is here - for all other button presses on this webpage - selenium has been working appropriately. What other ways can I try?
all_notes = WebDriverWait(driver,10).until(EC.presence_of_element_located(
(By.XPATH, '//*[#href="javascript:submitPage(\'V\',\'All Notes\',\'\');"]'))).click()
escape the single quotes
Try this Xpath...
//a[#class='viewFilter' and contains(text(), 'All Notes')]
What this does is verifies that the class is viewFilter and since classes can appear more than once also ensure that the link text is All Notes.

How to perform data fetch on button click on a built in html page using selenium

I am new to Selenium and I am trying to mimic user actions on a site to fetch data from a built in html page on button click. I am able to populate all the field details, but button click is not working, it looks like js code not running.
I tried many options like adding wait time, Action chain etc but it didnt work, i am providing site and code i have written.
driver = webdriver.Chrome()
driver.get("https://www1.nseindia.com/products/content/derivatives/equities/historical_fo.htm")
driver.implicitly_wait(10)
assigned values to all the other fields
driver.find_element_by_id('rdDateToDate').click()
Dfrom = driver.find_element_by_id('fromDate')
Dfrom.send_keys("02-Oct-2020")
Dto = driver.find_element_by_id('toDate')
Dto.send_keys("08-Oct-2020")
innerHTML = driver.execute_script("document.ready")
sleep(5)
getdata_btn = driver.find_element_by_id('getButton')
ActionChains(driver).move_to_element(getdata_btn).click().click().perform()
I recommend using a full xpath.
chrome.get("https://www1.nseindia.com/products/content/derivatives/equities/historical_fo.htm")
time.sleep(2)
print("click")
fullxpath = "/html/body/div[2]/div[3]/div[2]/div[1]/div[3]/div/div[1]/div/form/div[19]/p[2]/input"
chrome.find_element_by_xpath(fullxpath).click()
I have tried the button clicking and it worked with XPath ... I though its because of someone used the ID twice on a website, but I can not find it ... so i have no idea whats going wrong there ...
Good luck :)

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.

How do I interact with this iframe in selenium

textbox = driver.find_element_by_id('applicant.name')
doesn't work.
Unfortunately and I've tried every variation of inspect element, copy xpath , trying to identify the class name of the text boxes etc.
I want to be able to send some text to the input fields in the indeed-apply-widget seen here.
If you click 'apply now' (unfortunately I can't link it) you'll see the inputs are contained within 2 iframes.
Is there an easy way to access them?
Here's what I have so far:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://ca.indeed.com/cmp/Clearview-Plumbing-&-Heating/jobs/HVAC-Installer-Opening-6183dce44a9bfe10?sjdu=vQIlM60yK_PwYat7ToXhk42rccfWGklJDtD_zDpWBzDCfUEiSP2Zk-zLpFc6GNuF8wyV4_UaMyNFtpjETvX0fCpQXc3PxTbrGkwAMNkR5vGMtAfe9wNpTncItNgAIJHx' )
driver.find_element_by_class_name("indeed-apply-widget").click()
# move into the iframe
iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to_frame(iframe)
Updated Code (still unable to interact with the iframe)
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://ca.indeed.com/cmp/Clearview-Plumbing-&-Heating/jobs/HVAC-Installer-Opening-6183dce44a9bfe10?sjdu=vQIlM60yK_PwYat7ToXhk42rccfWGklJDtD_zDpWBzDCfUEiSP2Zk-zLpFc6GNuF8wyV4_UaMyNFtpjETvX0fCpQXc3PxTbrGkwAMNkR5vGMtAfe9wNpTncItNgAIJHx' )
driver.find_element_by_class_name("indeed-apply-widget").click()
# move into the iframe
path = driver.find_element_by_xpath("/html/body/div[5]/div/div[2]/iframe")
driver.switch_to_frame(path)
driver.find_element_by_xpath('//*[#id="applicant.name"]').sendKeys("TEST_NAME")
The element that you want is inside two nested IFRAMEs. The below code should work. You need to go into the first frame... and then the first nested frame. The rest should work at that point.
driver = webdriver.Firefox()
driver.get('http://ca.indeed.com/cmp/Clearview-Plumbing-&-Heating/jobs/HVAC-Installer-Opening-6183dce44a9bfe10?sjdu=vQIlM60yK_PwYat7ToXhk42rccfWGklJDtD_zDpWBzDCfUEiSP2Zk-zLpFc6GNuF8wyV4_UaMyNFtpjETvX0fCpQXc3PxTbrGkwAMNkR5vGMtAfe9wNpTncItNgAIJHx')
driver.find_element_by_css_selector("span.indeed-apply-button-label")).click()
driver.switch_to_frame(0)
driver.switch_to_frame(0)
driver.find_element_by_id("applicant.name")).send_keys(username)
driver.find_element_by_id("applicant.email")).send_keys(email)
driver.find_element_by_id("resume")).send_keys(resumePath)
driver.find_element_by_css_selector("a.button_content.form-page-next")).click()
driver.find_element_by_id("apply")).click()

Categories

Resources