Selenium WebDriver : AttributeError: 'WebDriver' object has no attribute 'ChromeOptions' - python

I made a successfull unit test with Selenium WebDriver python. This latter downloads a file in a custom location that I've defined, assert the file had been correctly downloded and delete it.
Here is its code :
import os
import time
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
options = webdriver.ChromeOptions() ;
prefs = {"download.default_directory" : "C:\\Users\\AminataWillane\\Desktop\\selenium_download"}
options.add_experimental_option("prefs",prefs);
driver = webdriver.Chrome(executable_path='./chromedriver',chrome_options=options)
driver.get('https://www.browserstack.com/test-on-the-right-mobile-devices');
gotit= driver.find_element(By.ID,'accept-cookie-notification');
gotit.click();
downloadcsv= driver.find_element(By.CSS_SELECTOR, '.icon-csv')
downloadcsv.click();
time.sleep(10)
#check file
try:
print('try started')
if os.path.isfile('C:\\Users\\AminataWillane\\Desktop\\selenium_download\\BrowserStack - List of devices to test on.csv'):
print("File download is completed and the file will be deleted")
time.sleep(5)
os.remove("C:\\Users\\AminataWillane\\Desktop\\selenium_download\\BrowserStack - List of devices to test on.csv")
print("File had been removed successfully")
except FileNotFoundError as er:
print("File Not Found !")
Then once I tried out the same logic while implementing Page Object Model, it isn't working :
here is the related code :
import os
import time
from seleniumpagefactory.Pagefactory import PageFactory
from selenium.webdriver.support.select import Select
from selenium.webdriver.chrome.options import Options
from test.test_download import options
class QA_download_me(PageFactory):
def __init__(self, driver):
self.driver = driver
options = driver.ChromeOptions();
prefs = {"download.default_directory": "C:\\Users\\AminataWillane\\Desktop\\selenium_download"}
options.add_experimental_option("prefs", prefs);
driver.Chrome(executable_path='./chromedriver', chrome_options=options)
locators = {
"documentation": ('ID', 'NavLinkDocumentation'),
"sdk": ('ID', 'NavLinkDocumentation1'),
"download_btn": ('XPATH', '//*[#id="server-root"]/div/div/main/div/div/div[2]/div/div[2]/div/div/a[1]'),
}
def download_me(self):
# create a service
self.documentation.click_button()
time.sleep(5)
self.sdk.click_button()
time.sleep(5)
self.download_btn.click_button()
time.sleep(10)
try:
print('try started')
if os.path.isfile(
'C:\\Users\\AminataWillane\\Desktop\\selenium_download\\MyriadSDK-latest.tgz'):
print("File download is completed and the file will be deleted")
time.sleep(5)
os.remove(
"C:\\Users\\AminataWillane\\Desktop\\selenium_download\\MyriadSDK-latest.tgz")
print("File had been removed successfully")
except FileNotFoundError as er:
print("File Not Found !")
Here is the error I've got :
ERROR: test_download_me (test.test_book_2.TestLoginTwo)
down= QA_download_me(self.driver)
File "C:\Users\AminataWillane\PycharmProjects\myProj\src\pages\download_me.py", line 15, in __init__
options = driver.ChromeOptions();
AttributeError: 'WebDriver' object has no attribute 'ChromeOptions'

in the second code snipper, when ur calling ChromeOptions() from driver, driver is only self.driver and hasn't yet been identified as selenium.webdriver.
try adding to imports:
from selenium import webdriver
and then say:
options = webdriver.ChromeOptions()
this also goes for when you instantiate your webdriver later (remove self.driver = driver from beginning of code):
self.driver = webdriver.Chrome(...)

Related

Docker selenium not redirecting on another page in django test

I have some issue with docker selenium. For example, I have tried it on local selenium using operadriver, so redirecting to another page, after submit form, was working.I want to see this result also in django selenium test, but I've just get selenium.common.exceptions.TimeoutException: Message: in waiting when url will change.
This is my test code
import os
import socket
import shutil
# from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
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.chrome.options import Options
from django.test import LiveServerTestCase
from django.conf import settings
# Create your tests here.
class LandFormTest(LiveServerTestCase):
host = socket.gethostbyname(socket.gethostname())
def setUp(cls):
selenium_url = 'http://selenium:4444/wd/hub'
options = Options()
options.add_argument('--no-sandbox')
options.add_argument('--headless')
options.add_argument("--disable-dev-shm-usage")
options.add_argument("--ignore-certificate-errors")
# options.add_argument("My user agent")
options.add_argument(f"window-size=1920,1080")
cls.driver = webdriver.Remote(
command_executor=selenium_url,
desired_capabilities=DesiredCapabilities.CHROME,
options=options
)
def test_form(self):
try:
driver = self.driver
domain = self.live_server_url.split('//')[1].split(':')[0]
if not settings.BASE_DIR.joinpath(f'templates/lands/{domain}').is_dir():
src = f'templates/lands/quantum.localhost'
dest = f'templates/lands/{domain}'
shutil.copytree(src, dest)
driver.get(f'{self.live_server_url}/api/v1/test/?ai=2&gi=5')
user_firstname = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.NAME, "firstname"))
)
current_url = driver.current_url
user_firstname = driver.find_element(By.NAME, 'firstname')
user_lastname = driver.find_element(By.NAME, 'lastname')
user_email = driver.find_element(By.NAME, 'email')
user_phone = driver.find_element(By.NAME, 'phone')
user_firstname.send_keys('test')
user_lastname.send_keys('test')
user_email.send_keys('test#gmail.com')
user_phone.send_keys('+(846)411-36-00')
user_phone.submit()
WebDriverWait(driver, 10).until(EC.url_changes(current_url))
print(driver.current_url)
print(driver.page_source)
assert 'Hello World' in driver.page_source
except Exception as e:
raise(e)
def tearDown(self):
self.driver.quit()
My /api/v1/test/ url get static and template in folder by domain name, so I copy the default folder "quantum.localhost" and rename it to ip of docker. The main problem is that is working locally with driver, but not with docker and django. Want to notice that I am also tried to use firefox selenium. Thanks for help!

Why isn't the webpage loding while scraping linkedin?

In this code I am trying to scrape a Linkedin profile using Selenium
but the driver is not able to load the page I guess IP has been
blocked and I am new to the concept of proxy rotating or any concept
that is used in such cases. It would be a great help if you could help
me understand how this is done.
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome(executable_path=r'C:\Users\chromedriver.exe')
def linkedin_login():
global driver
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option('excludeswitches', ['enable-automation'])
options.add_experimental_option("detach", True)
try:
driver.get('https://www.linkedin.com/login')
username = 'username'
password = 'password'
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, 'username'))).send_keys(username)
driver.find_element_by_id('password').send_keys(password)
driver.find_element_by_class_name('btn__primary--large from__button--floating').click()
time.sleep(8)
except ImportError:
print('Closing')
def search_profiles():
search_profile = input('What profile do you want to search?')
search_profile = search_profile.split()
search = search_profile[0] + "%20" + search_profile[1]
The "Sign In" button's class name is incorrect, specifically is missing a dot(.)
Instead of:
driver.find_element_by_class_name('btn__primary--large from__button--floating').click()
Use:
driver.find_element_by_class_name('btn__primary--large.from__button--floating').click()
That will click the button.
Also, if you run the code you shared, you are calling the webdriver but not calling your function.
I tested the below code and worked fine (remember to update your path and LinkedIn credentials):
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome(executable_path='/home/armentaahumada/Downloads/chromedriver')
def linkedin_login():
global driver
options = webdriver.ChromeOptions()
options.add_argument("start-maximized")
options.add_experimental_option('excludeswitches', ['enable-automation'])
options.add_experimental_option("detach", True)
try:
driver.get('https://www.linkedin.com/login')
username = 'username'
password = 'password'
WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.ID, 'username'))).send_keys(username)
driver.find_element_by_id('password').send_keys(password)
driver.find_element_by_class_name('btn__primary--large.from__button--floating').click()
time.sleep(8)
except ImportError:
print('Closing')
def search_profiles():
search_profile = input('What profile do you want to search?')
search_profile = search_profile.split()
search = search_profile[0] + "%20" + search_profile[1]
linkedin_login()

"Failed - Download error" while download a file using Selenium Python

I was trying to download a file using selenium but getting "Failed - Download error".
I tried to disable the safe browsing but it didn't work.
I have attached the screenshot and code as well.
logs:
DevTools listening on ws://127.0.0.1:53738/devtools/browser/d75dfd5b-1e3e-45c5-8edd-adf77dd9adb1
[2572:2724:0717/104626.877:ERROR:device_event_log_impl.cc(208)] [10:46:26.877] Bluetooth: bluetooth_adapter_winrt.cc:1074 Getting Default Adapter failed.
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
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
import time
import csv
from selenium.webdriver.chrome.options import Options
link_list = [
"stewartwatson.co.uk",
"peterkins.com",
"gavin-bain.co.uk",
"martinco.com",
"tmmsolicitors.co.uk",
"corecitilets.co.uk",
"coxandco.co",
"dunechtestates.co.uk",
"bidwells.co.uk",
"kwad.co.uk",
]
options = webdriver.ChromeOptions()
options.add_experimental_option("prefs", {
"download.default_directory": r"C:\\Users\\Awais\\projects\\selenium\\web_email_extractor\\csv",
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": False,
"safebrowsing.ebabled": "false"
})
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://www.webemailextractor.com")
try:
driver.find_element_by_xpath('//button[contains(text(),"Close")]').click()
except:
pass
for i in link_list[0:5]:
text_area = driver.find_element_by_xpath('//textarea[#placeholder="Enter domain/websites list"]')
text_area.send_keys(i)
text_area.send_keys(Keys.ENTER)
submit = driver.find_element_by_xpath('//input[#value="Extract Email"]').click()
try:
btn = WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.XPATH, "//span[contains(text(), ' Process Completed')]")))
time.sleep(3)
csv_download = driver.find_element_by_xpath('//button[#class="dt-button buttons-csv buttons-html5"]').click()
except Exception as e:
print(e)
It worked when I removed the "r" from the path
"download.default_directory": r"C:\\Users\\Awais\\projects\\selenium\\web_email_extractor\\csv",
to:
"download.default_directory": "C:\\Users\\Awais\\projects\\selenium\\web_email_extractor\\csv",
Dear: When we configure the options of selenium is what will be defined in its configurations and as you write the route so considers it in the first photo you will see a well-configured route and a bad one, note bars there is the difference enter image description here
enter image description here

Fixture is not visible when fixture is defined in a different file in pytest

I have 2 files:
conftest.py
import pytest
from selenium import webdriver
driver = None
#pytest.fixture
def browserSetAndClose():
global driver
EXE_PATH = r'C:\Users\1602746\Softwares\chromedriver.exe'
chromeOptions = webdriver.ChromeOptions()
chromeOptions.add_experimental_option('useAutomationExtension', False)
driver = webdriver.Chrome(executable_path = EXE_PATH, options = chromeOptions,
desired_capabilities = chromeOptions.to_capabilities())
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://the-internet.herokuapp.com/')
yield driver
driver.quit()
xzbc.py
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from browser_factory import conftest
def test_abTest(browserSetAndClose):
wait = WebDriverWait(conftest.driver, 15)
wait.until(expected_conditions.element_to_be_clickable((By.XPATH, "//a[starts-with(#href, '/abtest')]"))).click()
a = wait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, "h3"))).text
assert 'A/B Test' in a
The problem is I keep getting an error-
fixture 'browserSetAndClose' not found
when I run the test case function test_abTest.
I tried everything but all in vain.
Also, here is an image of the project structure to show that the aforementioned files are in different directories:

Selenium - Python webdriver path error system can't find the path specified

Please help, whats wrong with the FF profile. I want to save a file from the website using Firefox and python webdriver
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
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.support.select import Select
import os
"""from bs4 import BeautifulSoup"""
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir", os.getcwd())
fp.set_preference("browser.helperApps.neverAsk.saveToDisk", "text/html")
driver = webdriver.Firefox(firefox_profile=fp)
driver.get("http://achecker.ca/checker/index.php")
assert "Web Accessibility Checker" in driver.title
options = driver.find_element_by_link_text("Options")
options.click()
check_WCAG10 = driver.find_element_by_id("radio_gid_4")
check_WCAG10.click()
elem = driver.find_element_by_id("checkuri")
input_url = "naturasiberica.ru"
elem.send_keys(input_url)
elem.send_keys(Keys.RETURN)
# wait for result
try:
element_exp_form = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "fileselect")))
except:
driver.quit()
export_format = Select(driver.find_element_by_id("fileselect"))
export_format.select_by_value("html")
get_file = driver.find_element_by_id("validate_file_button")
get_file.click()
# wait for file_download
try:
element_exp_form = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "fileselect"))
)
finally:
driver.quit()
driver.quit()
Then I have an error:
[Error 3] The system cannot find the path specified: 'c:\users\semashko\appdata\local\temp\tmpr7lojx/.'

Categories