Unable to import selenium webdriver from within a function - python

I have a few scripts, wherein I am required to import a few modules everytime. To avoid using the import statements everytime I write a new script, I tried to write a function as follows so that I can import the function instead. Here's how wrote the code for that :
def mylibs():
import selenium
from selenium import webdriver
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
return
mylibs()
But when I am running the next line of the code- which should use the webdriver imported above to launch an instance of the chrome browser :
browser = webdriver.Chrome(r"c:\users\nila9\drivers\chromedriver.exe")
I am getting an error like "webdriver not defined", so the browser fails to launch.
I am not able to understand what I am getting wrong here...I also tried to do it without the return also, but same result.
If this works, I can then import the module into any other script, whenever I need to use the block of import codes.
Any help appreciated.

try
driver = webdriver.Chrome(executable_path="C:\Users\nila9\drivers\chromedriver.exe")
or
driver = webdriver.Chrome("C:\Users\nila9\drivers\chromedriver.exe")

Related

How to enter file path?

How can I do to type something in the field of the image below?
I've tried without success:
from threading import local
import pandas as pd
import pyautogui
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait.until(EC.presence_of_element_located((By.XPATH,"//input[#type='file']"))send_keys("C:/Users/my_user/Downloads/doch.jpeg")
for index, row in df.iterrows():
actions.send_keys((row["message"]))
actions.perform()
The only palliative solution was:
pyautogui.write((row["photo"]))
pyautogui.press("enter")
I don't want to use pyautogui as it uses the keyboard command and I can't do anything on the computer while the code is running.
Selenium can't upload files using the Windows select file option, so you'll have to do something else - you might be able to use the send_keys function, i.e.:
elem = driver.find_element(By.XPATH, "//input[#type='file']")
elem.send_keys('C:\\Path\\To\\File')
Note that this may not work, depending on the type of input, and you may be able to instead simulate a drag-and-drop operation if the website supports this.
See How to upload file ( picture ) with selenium, python for more info
For windows path you need double backslashes. Try this:
wait.until(EC.presence_of_element_located((By.XPATH,"//input[#type='file']"))send_keys("C:\\Users\\my_user\\Downloads\\doch.jpeg")

On running my selenium python script, i am getting processed finished with exit code 0 in the console but my results are not showing up

Nothing is getting printed in console on running the script. Browser is not launching
In console- Process finished with exit code (0)
Script -
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import pytest
import time
from webdriver_manager.firefox import GeckoDriverManager
from webdriver_manager.microsoft import EdgeChromiumDriverManager
def test_google():
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.implicitly_wait(5)
driver.get("https://www.google.com/")
assert driver.title == 'Sign in – Google accounts'
print(driver.title)
I think you have created the method but didn't call the method that's why i think
Thanks for all the answers . But i was able to solve the problem in 2 ways :
Calling the method solved it
I reinstalled everything and then run it . it worked

NameError: name 'WebDriverWait' is not defined

I have a Python code written by a frined which actually worked perfectly just a few weeks ago and now is causing some problems.
The code takes a google images search link from a csv file and using Selenium Webdriver (Chrome), gives back a link to the first image on the search page.
What could be the reason for this error? (NameError: name 'WebDriverWait' is not defined)
Thank!
That error typically means you are missing this import:
from selenium.webdriver.support.ui import WebDriverWait
Import two things:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

Python expected_conditions don't always work

I'm having an odd problem trying to web scrape some data from ESPN. I have the below code that sometimes works as intended, but sometimes will get hung up trying to log in. It really seems random, and I'm not sure what's going on.
import time
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
driver = webdriver.Chrome(r'Source')
driver.get("http://games.espn.go.com/ffl/signin")
WebDriverWait(driver,1000).until(EC.presence_of_all_elements_located((By.XPATH,"(//iframe)")))
frms = driver.find_elements_by_xpath("(//iframe)")
driver.switch_to_frame(frms[2])
time.sleep(2)
WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,'(//input)[1]')))
driver.find_element_by_xpath("(//input)[1]").send_keys("Username")
driver.find_element_by_xpath("(//input)[2]").send_keys("password")
driver.find_element_by_xpath("//button").click()
driver.switch_to_default_content()
time.sleep(2)
When I run the code as is, it often times times out during the second "WebDriverWait", despite the page having fully loaded in chrome. If I take that line out, I then will get an error message that reads:
"selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:"
You check this xpath? Apparently it is not correct, you can try it on the browser console.
$x('yourxpath')

Selenium Webdriver: How to take full page screenshot using FireShot written in Python

In Selenium Webdriver, I am looking to be able to take a full page screenshot using FireShot executed from a Python script.
I have the following code so far:
import unittest
import execjs
from execjs import get
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
class PythonOrgSearc(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome('/usr/bin/chromedriver');
def test_login_and_make_payment_on_account(self):
driver = self.driver;
driver.set_window_size(1024,768);
# Log in to My Account
driver.get("https://www.mywebsite.com");
self.assertIn("Sign In", driver.title);
driver.save_screenshot('/Users/username/Documents/Selenium_Test/01a_login.png');
# Enter username
user = driver.find_element_by_id("EmailOrAccountNumber");
user.send_keys("user#me.co.uk");
# Enter password and submit form
password = driver.find_element_by_id("Password");
password.send_keys("password123");
driver.save_screenshot('/Users/username/Documents/Selenium_Test/01b_login_filled.png');
password.send_keys(Keys.RETURN);
# Confirm logged into My Account
self.assertIn("Account Summary", driver.title);
driver.save_screenshot('/Users/username/Documents/Selenium_Test/02a_My_Account.png');
def tearDown(self):
self.driver.close();
if __name__ == "__main__":
unittest.main();
I have installed PyExecJS, but have no idea how I can begin using the FireShot API to replace the current save_screenshot functions used in the code. Thank you for any steer or guidance you can provide.
I think it is better to use driver.execute_script command to execute your javascript in the browser, but if you want to check a markup, perhaps, applitools could help you

Categories