Selenium Webdriver: NameError name 'firefox' is not defined - selenium

I'm trying to write this code using Selenium and Python:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://demo.guru99.com/test/login.html')
from selenium.webdriver.common.keys import Keys
email = firefox.find_element_by_xpath('//*[#id="email"]')
email.send_keys('user#gmail.com')
passwd = firefox.find_element_by_xpath('//*[#id="passwd"]')
passwd.send_keys('123456')
But I don't understand why this error occured, please help me

In your code, you are making a an instance of the webdriver.Firefox() object and calling it browser
browser = webdriver.Firefox()
Later on in your code, you try to find an element by xpath using a varible called firefox
email = firefox.find_element_by_xpath('//*[#id="email"]')
The problem is that that firefox was never actually created, I think what you meant to do is
email = browser.find_element_by_xpath('//*[#id="email"]')

You are defining the variable browser as a webdriver object. You then attempt to use firefox as a webdriver object, but you never defined the variable firefox. This is one way to solve your problem. You're better off calling the variable browser, rather than firefox, because then you can just change the browser type in your first line of code and the code will not be confusing.
browser = webdriver.Firefox()
browser.get('http://demo.guru99.com/test/login.html')
from selenium.webdriver.common.keys import Keys
email = browser.find_element_by_xpath('//*[#id="email"]')
email.send_keys('user#gmail.com')
passwd = browser.find_element_by_xpath('//*[#id="passwd"]')
passwd.send_keys('123456')

Related

Selenium element selection issues and VSCode bug? Automate the Boring Stuff chapter 12

I'm attempting to replicate this code:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('https://inventwithpython.com')
try:
elem = browser.find_element_by_class_name(' cover-thumb')
print('Found <%s> element with that class name!' % (elem.tag_name))
except:
print('Was not able to find an element with that name.')
But it keeps returning the exception. I'm running this on mac w. vscode and there are few things off.
find_element_by_class_name method doesn't seem to register as a method.
Everytime I run this Intellicode prompts get disabled
I can't run this at all on Chrome as it crashes the chrome browsers
I've also searched online for driver issues and have done webdriver with the chrome driver path. Didn't work either
This is the error I'm getting if run it without try and except.
elem = browser.find_element_by_class_name(' cover-thumb') ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'WebDriver' object has no attribute 'find_element_by_class_name'
Selenium removed that method in version 4.3.0. See the CHANGES: https://github.com/SeleniumHQ/selenium/blob/a4995e2c096239b42c373f26498a6c9bb4f2b3e7/py/CHANGES
Selenium 4.3.0
* Deprecated find_element_by_* and find_elements_by_* are now removed (#10712)
* ...
You now need to use:
driver.find_element("class name", "VALUE_OF_CLASS_NAME")
Eg:
driver.find_element("class name", "cover-thumb")
But if a class name has multiple segments, use the dot notation from a CSS Selector:
driver.find_element("css selector", "img.cover-thumb")

find_element_by_name selenium python question

I'm a beginner trying to use selenium to automate browser interactions through an undetectable chrome browser.
The code i've done so far is below (you have no idea the time i've sunk into 5 lines).
I've tried so many iterations of the same code that I've lost sanity. This SHOULD work?
This is almost copied exactly from a youtube video now, there were some other ideas that youtubers did use but I didn't understand the coding so I haven't touched them. Anything #'d can be ignored or assumed that i've played with it and failed.
import autogui, sys, time, webbrowser, selenium
import undetected_chromedriver.v2 as uc
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common import action_chains
#Open Browser and visit website.
driver = uc.Chrome()
driver.get('https://www.iqrpg.com/game.html')
time.sleep(5)
#Complete username and password fields
userN = 'Gary'
passW = 'Barry'
find_element_by_name('login_username').send_keys(userN)
#find_element_by_name('login_password').send_keys(passW)
#driver.find_element_by_css_selector("input[type=\"submit"
#userField =
#passField = driver.find_element(By.ID, "passwd-id")
#search_box = driver.find_element_by_name('Battling')
#search_box.send_keys('ChromeDriver')
#search_box.submit()
#time.sleep(5)
1.Expecting the browser to open, forcibly logging you out due to selenium chrome
2. select name='login_username', send key the string saved under userN
3. same for password
4. click login (not yet coded, but plans)
In the latest Selenium with Python, you cannot use - driver.find_element_by_name.
Instead, you have to use: driver.find_element
from selenium.webdriver.common.by import By
driver.find_element(By.NAME, "login_username").send_keys("userN")
driver.find_element(By.NAME, "login_password").send_keys("passW")

Python move_to_element().click() is not pressing a right element visible on the screen or returns the error. A trial code is included

I try to interact with the elements (button at this scenario) inside Disqus iframe on this webpage:
This is my trial code:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time
path_to_chromedriver = r"c:\users\tv21\source\repos\chromedriver.exe"
driver = webdriver.Chrome(executable_path=path_to_chromedriver)
driver.maximize_window()
url = "https://www.postoj.sk/91472/po-navsteve-kina-si-precitajte-aj-kniznu-predlohu"
driver.get(url)
time.sleep(5)
button_to_close = driver.execute_script("return document.querySelector('body').querySelector('div.grv-dialog-host').shadowRoot.querySelector('div').querySelector('div.buttons-wrapper').querySelector('button.sub-dialog-btn.block_btn')")
ac = ActionChains(driver)
ac.move_to_element(button_to_close).click().perform()
open_discussion = driver.find_element_by_class_name('article-disqus-wrapper')
driver.execute_script("arguments[0].setAttribute('style','display: block;')", open_discussion)
disqus_thread = driver.find_element_by_id("disqus_thread")
iframe_element = disqus_thread.find_element_by_tag_name("iframe")
driver.switch_to.frame(iframe_element)
time.sleep(1)
button_to_load_more = driver.find_element_by_partial_link_text("Nahraj viac komentárov")
ac = ActionChains(driver)
ac.move_to_element(button_to_load_more).click().perform()
The issue is the last command:
ac.move_to_element(button_to_load_more).click().perform()
which shows an error: "move target out of bounds"
I tried instead:
button_to_load_more.click()
and
driver.execute_script("arguments[0].click();", button_to_load_more)
which both work completely fine as the alternatives and I can click the button.
However, I try to understand the reason for being out of bounds when using move_to_element(). I get exactly the same error always when I want to hover over any elements inside Disqus iframe too.
Can anyone help me to fix it or explain to me how to fix it?
First one dint worked because of the known issue in selenium,i guess you are using 3.4 hence facing this.(But it should work after trying newer version of selenium)
Some of the useful links fyr
Selenium MoveTargetOutOfBoundsException even after scrolling to element
https://github.com/SeleniumHQ/selenium/issues/4148

Selenium action 'move_to_element' doesn't work in Safari because of usupported 'pause' command

The next command is failed on Safari browser during automation testing:
ActionChains(driver).move_to_element(searchInput).perform()
Exception:
InvalidArgumentException: Message: Encountered key input source with
invalid 'value' in payload: {actions = ({duration = 0;type =
pause;});
id = key;
type = key;}
The whole refined test example:
def test_safari2(self):
driver = webdriver.Safari()
driver.get('https://www.wikipedia.org')
locator = (By.ID, 'searchInput')
# 1. the line below is passed
searchInput = WebDriverWait(driver, timeout=30).until(expected_conditions.visibility_of_element_located(locator))
# 2. the line below is failed in Safari, but passed in Chrome, FF
ActionChains(driver).move_to_element(searchInput).perform()
However! If self.w3c_actions.key_action.pause() is commented inside action move_to_element(), then the whole Action chains works!
def move_to_element(self, to_element):
"""
Moving the mouse to the middle of an element.
:Args:
- to_element: The WebElement to move to.
"""
if self._driver.w3c:
self.w3c_actions.pointer_action.move_to(to_element)
# self.w3c_actions.key_action.pause()
else:
self._actions.append(lambda: self._driver.execute(
Command.MOVE_TO, {'element': to_element.id}))
return self
The similar situation with other actions.
My question is:
Is it is known limitation of Safari? And therefore ActionChais command could not be use for Selenium + Safari? Or there is some configuration pecularity?
My test runner configuration:
OS: Mac HighSierra 10.13.6
Safari 12.0 (13606.2.11)
Selenium: 3.14.1
Python: 2.7.14
Safari is started with w3c capabilities and protocol (i.e. driver.w3c=True)
Issue background:
I have an enough developed framework with a lot of actions and tests that work Ok for Chrome and Firefox. Now I'm trying to extend coverage for Safari browser also. So, that is why I'm searching for solution for not working ActionChains
Workaround by wrapping ActionChains class so that key_action.pause is not used (which does not seem to serve any important purpose):
import selenium.webdriver
class ActionChains(selenium.webdriver.ActionChains):
def __init__(self, driver):
super(ActionChains, self).__init__(driver)
if driver.name in ('Safari', 'Safari Technology Preview'):
self.w3c_actions.key_action.pause = lambda *a, **k: None

Selenium's WebDriver.execute_script() returns 'None'

My program is having trouble getting an existing class from a webpage using Selenium. It seems that my WebDriver.execute_script function is not working.
import urllib
from selenium import webdriver
#Path to the chromedriver is definitely working fine.
path_to_chromedriver = 'C:\Users\Ben\Desktop\Coding\FreeFoodFinder\chromedriver.exe'
browser = webdriver.Chrome(executable_path = path_to_chromedriver)
url = 'http://www.maidservicetexas.com/'
browser.implicitly_wait(30)
browser.get(url)
content = browser.execute_script("document.getElementsByClassName('content')");
#Just printing the first character of the returned content's toString for now. Don't want the whole thing yet.
#Only ever prints 'N', the first letter of 'None'...so obviously it isn't finding the jsgenerated content even after waiting.
print content
My program returns 'None,' which tells me that the javascript function is not returning a value/being executed. Chrome's web dev tools tell me that 'content' is certainly a valid class name. The webpage isn't even dynamically generated (my eventual goal is to scrape dynamic content, which is why I make my WebDriver wait for 30 seconds before running the script.)
Return the value:
content = browser.execute_script("return document.getElementsByClassName('content');");