I have two files one is Login_test.py and the other is Financial_Account_Balance.py. When I run the Login file, it works but I want after the system Login, it should check the Financial Account. I keep getting error when I instantiate the Class in the Financial Account Script.
Object has no attribute 'driver'
Below is my code for both files
Login_test
import unittest
from selenium import webdriver
import time
class LoginForm(unittest.TestCase):
def __init__(self, driver = None):
#super().__init__(driver)
if driver is not None:
self.driver = driver
else:
self.setUp()
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r"..\browser\chromedriver.exe")
print("Running Set Up method")
print(self.driver)
self.test_result = None
def test_Login(self):
# We wrap this all in a try/except so we can set pass/fail at the end
try:
# load the page url
print('Loading Url')
self.driver.get('http://localhost:4200/')
# maximize the window
#print('Maximizing window')
self.driver.maximize_window()
# we'll start the login process by entering our username
print('Entering username:')
self.driver.find_element_by_name('username').send_keys('mobile#******.com')
# then by entering our password
print('Entering password:')
self.driver.find_element_by_id('pass').send_keys('*****')
# now we'll click the login button
print('Logging in')
self.driver.find_element_by_class_name("submit").click()
time.sleep(25)
self.test_result = 'pass'
except AssertionError as e:
# log the error message
self.test_result = 'fail'
raise
"""
def tearDown(self):
print("Done with session")
self.driver.quit()
"""
if __name__ == '__main__':
unittest.main()
Financial Account File
from Unit_Test_Files.Login_test import *
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.by import By
import time
import logging
import unittest
class FinancialAccountBalance:
#logf = open("Financial_Account_Balance_exception.log", "w")
def __init__(self, driver = None):
if driver is not None:
self.driver = driver
else:
print('Financial Account Balance Testing Started...')
self.test_finacial()
def setUp(self):
print(self.driver)
print("setup method running")
self.test_finacial()
def test_finacial(self):
try:
print(self.driver)
self.driver.find_element_by_xpath(
'/html/body/chankya-app/chankya-layout/div/ng-sidebar-container/div/div/section/div/div[2]/app-home/div/div/div/div/div[2]/div/input').send_keys(
'Financial Account Balance')
time.sleep(2)
self.driver.find_element_by_xpath(
'/html/body/chankya-app/chankya-layout/div/ng-sidebar-container/div/div/section/div/div[2]/app-home/div/div/div/div/div[2]/div/input').send_keys(
Keys.ENTER)
time.sleep(2)
WebDriverWait(self.driver, 10).until(
EC.presence_of_all_elements_located(
(By.XPATH, '//html/body/chankya-app/chankya-layout/div/ng-sidebar-container'
'/div/div/section/div/div[2]/app-home/div/div/div/div/div[4]'
'/div/div/table/tbody/tr')))
result = self.driver.find_element_by_xpath(
'(/html/body/chankya-app/chankya-layout/div/ng-sidebar-container/div/div/section/div/div[2]/app-home/div/div/div/div/div[4]/div/div/table/tbody/tr)[1]')
result.click()
time.sleep(15)
logging.basicConfig(filename='Financial_Account_Balance.log', level=logging.INFO, filemode='w',
format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p ')
logging.info('Date and Time \nReport: Financial Account Balance Automation Test is Successful!!! \n')
print('Financial Account Balance Automation Test is Successful!!!')
except AssertionError as e:
# log the error message
self.test_result = 'fail'
raise
def test_verify(self):
lf = LoginForm()
lf.test_Login()
self.test_finacial()
if __name__ == '__main__':
fa = FinancialAccountBalance()
fa.test_verify()
Error I get when I run the Financial Account file
"C:\Users\Apollo Universe IDS\.virtualenvs\test-cM_nBYrn\Scripts\python.exe" C:/Users/Public/Documents/test/Financial_Module/Financial_Account_Balance.py
Financial Account Balance Testing Started...
Traceback (most recent call last):
File "C:/Users/Public/Documents/test/Financial_Module/Financial_Account_Balance.py", line 68, in <module>
fa = FinancialAccountBalance()
File "C:/Users/Public/Documents/test/Financial_Module/Financial_Account_Balance.py", line 21, in __init__
self.test_finacial()
File "C:/Users/Public/Documents/test/Financial_Module/Financial_Account_Balance.py", line 30, in test_finacial
print(self.driver)
AttributeError: 'FinancialAccountBalance' object has no attribute 'driver'
def __init__(self, driver = None):
if driver is not None:
self.driver = driver
else:
print('Financial Account Balance Testing Started...')
self.test_finacial()
if driver is none , you are not creating any self.driver . so that class will not have any instance variable driver in that case
fix:
class FinancialAccountBalance:
#logf = open("Financial_Account_Balance_exception.log", "w")
def __init__(self, driver = None):
if driver is not None:
self.driver = driver
else:
print('Financial Account Balance Testing Started...')
self.setUp()
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r"..\browser\chromedriver.exe")
print(self.driver)
print("setup method running")
self.test_finacial()
Related
I am trying to take an account of over 1,000,000 followers on instagram and add their usernames to a txt file. I am trying to use Selenium for this but my authorization for login fails every time i login. Any advice on how to get around this? I assume the site believes this is a hack but im not sure.
from selenium import webdriver as web
from selenium.webdriver.common.keys import Keys
import time
import random
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.chrome.options import Options
bot_username = 'null'
bot_password = 'Null'
profiles = ['Enter Here']
amount = 300
# 'usernames' or 'links'
result = 'usernames'
us = ''
class Instagram():
def __init__(self, username, password):
self.username = username
self.password = password
options = Options()
options.add_experimental_option("excludeSwitches", ["enable-logging"])
self.browser = web.Chrome("chromedriver",options=options)
self.browser.set_window_size(400, 900)
def close_browser(self):
self.browser.close()
self.browser.quit()
def login(self):
browser = self.browser
try:
browser.get('https://www.instagram.com')
time.sleep(random.randrange(3, 5))
# Enter username:
username_input = browser.find_element_by_name('username')
username_input.clear()
username_input.send_keys(self.username)
time.sleep(random.randrange(2, 4))
# Enter password:
password_input = browser.find_element_by_name('password')
password_input.clear()
password_input.send_keys(self.password)
time.sleep(random.randrange(1, 2))
password_input.send_keys(Keys.ENTER)
time.sleep(random.randrange(3, 5))
print(f'[{self.username}] Successfully logged on!')
except Exception as ex:
print(f'[{self.username}] Authorization fail')
self.close_browser()
def xpath_exists(self, url):
browser = self.browser
try:
browser.find_element_by_xpath(url)
exist = True
except NoSuchElementException:
exist = False
return exist
def get_followers(self, users, amount):
browser = self.browser
followers_list = []
for user in users:
browser.get('https://instagram.com/' + user)
time.sleep(random.randrange(3, 5))
followers_button = browser.find_element_by_xpath('/html/body/div[1]/section/main/div/ul/li[2]/a/span')
count = followers_button.get_attribute('title')
if ',' in count:
count = int(''.join(count.split(',')))
else:
count = int(count)
if amount > count:
print(f'You set amount = {amount} but there are {count} followers, then amount = {count}')
amount = count
followers_button.click()
loops_count = int(amount / 12)
print(f'Scraping. Total: {amount} usernames. Wait {loops_count} iterations')
time.sleep(random.randrange(8,10))
followers_ul = browser.find_element_by_xpath("/html/body/div[6]/div/div/div[2]")
time.sleep(random.randrange(5,7))
try:
for i in range(1, loops_count + 1):
browser.execute_script("arguments[0].scrollTop = arguments[0].scrollHeight", followers_ul)
time.sleep(random.randrange(8, 10))
all_div = followers_ul.find_elements_by_tag_name("li")
for us in all_div:
us = us.find_element_by_tag_name("a").get_attribute("href")
if result == 'usernames':
us1 = us.replace("https://www.instagram.com/", "")
us = us1.replace("/", "")
followers_list.append(us)
time.sleep(1)
f3 = open('userlist.txt', 'w')
for list in followers_list:
f3.write(list + '\n')
print(f'Got: {len(followers_list)} usernames of {amount}. Saved to file.')
time.sleep(random.randrange(3, 5))
except Exception as ex:
print(ex)
self.close_browser()
return followers_list
bot = Instagram(bot_username, bot_password)
bot.login()
followers = bot.get_followers(profiles, amount)
I'm currently using Python and Selenium to loop my server for specific tasks to complete, I have tried to do 2 things, to speed up the process they are:
To use options.add_argument(f"user-data-dir={script_directory}\\profile") in the Chrome driver initiasation to avoid having to log in all the time.
To try and reuse the same browser window instead of closing and then re-opening the browser all the time.
Code:
#!/usr/bin/env python
import pathlib
import time
import urllib.parse
import requests
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
USER = "..."
PASS = "..."
def upload_to_server(link, redirect, unique_hash):
try:
requests.get(
"https://www.example.com/crons.php?cronUploadToServer=1&link={0}&redirect={1}&hash={2}".format(link,
redirect,
unique_hash))
except Exception as e:
print(e)
def download_from_server():
try:
server = requests.get("https://www.example.com/crons.php?cronDownloadFromServer=1")
return server.text.strip()
except Exception as e:
print(e)
# tear down chrome.
def tear_down(_driver):
_driver.quit()
_driver.close()
def check_for_tasks():
if download_from_server() == "NO_TASKS":
print("--> NO TASKS")
else:
# init the chrome driver.
def init_driver(using_linux, proxy):
script_directory = pathlib.Path().absolute()
try:
options = Options()
options.headless = False
options.add_argument('start-maximized')
options.add_argument('--disable-popup-blocking')
options.add_argument('--disable-notifications')
options.add_argument('--log-level=3')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--ignore-ssl-errors')
options.add_argument(f"user-data-dir={script_directory}\\profile")
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option("detach", True)
prefs = {'profile.default_content_setting_values.notifications': 2}
options.add_experimental_option('prefs', prefs)
if proxy == "0.0.0.0:0":
print("--> PROXY DISABLED ...")
else:
print("--> PROXY: " + str(proxy) + " ...")
options.add_argument('--proxy-server=%s' % proxy)
if using_linux:
return webdriver.Chrome(options=options)
else:
return webdriver.Chrome(options=options)
except Exception as e:
print(e)
# create session.
driver = init_driver(False, "0.0.0.0:00")
# starting URL.
driver.get('https://www.example.com/logon')
# click recorded.
def topcashback_click(_driver):
try:
_driver.get('https://www.example.com/Earn.aspx?mpurl=shein&mpID=17233')
if "redirect.aspx?mpurl=shein" in _driver.current_url:
return _driver.current_url
else:
return False
except Exception as e:
print(e)
# already logged in check.
if ">Account</span>" in driver.page_source:
print("--> LOGGED IN (ALREADY) ...")
driver.get('https://www.SITE.CO.UK/Earn.aspx?mpurl=shein&mpID=17233')
try:
server = download_from_server()
data_from_server = server.split('|')
link = topcashback_click(driver)
print("--> LINK --> " + link)
time.sleep(4)
if link != driver.current_url:
print("--> LINK (REDIRECT) --> " + driver.current_url)
upload_to_server(urllib.parse.quote_plus(link),
urllib.parse.quote_plus(
driver.current_url.replace('https://www.example.com', data_from_server[0])),
data_from_server[1])
# print(driver.current_url.replace('https://www.example.com', data_from_server[0]))
print("--> LINK UPLOADED TO THE DB ...")
# tear_down(driver)
except Exception as e:
print(e)
else:
# TopCashBack login for the first time.
def topcashback_login(_driver):
_driver.get('https://www.example.com/logon')
# small sleep to let the page load.
time.sleep(1)
_driver.find_element(By.XPATH, '//*[#id="txtEmail"]').send_keys(USER)
time.sleep(1)
_driver.find_element(By.XPATH, '//*[#id="loginPasswordInput"]').send_keys(PASS)
time.sleep(1)
_driver.find_element(By.XPATH, '//*[#id="Loginbtn"]').click()
time.sleep(5)
if ">Account</span>" in _driver.page_source:
return True
else:
return False
def topcashback_click(_driver):
try:
_driver.get('https://www.SITE.CO.UK/Earn.aspx?mpurl=shein&mpID=17233')
if "redirect.aspx?mpurl=shein" in _driver.current_url:
return _driver.current_url
else:
return False
except Exception as e:
print(e)
if topcashback_login(driver):
try:
print("--> LOGGED IN ...")
server = download_from_server()
data_from_server = server.split('|')
link = topcashback_click(driver)
print("--> LINK --> " + link)
time.sleep(4)
if link != driver.current_url:
print("--> LINK (REDIRECT) --> " + driver.current_url)
upload_to_server(urllib.parse.quote_plus(link),
urllib.parse.quote_plus(
driver.current_url.replace('https://www.example.com',
data_from_server[0])),
data_from_server[1])
# print(driver.current_url.replace('https://www.example.com', data_from_server[0]))
print("--> LINK UPLOADED TO THE DB ...")
# tear_down(driver)
except Exception as e:
print(e)
else:
print("--> ERROR --> DEBUG TIME ...")
tear_down(driver)
if __name__ == "__main__":
while True:
check_for_tasks()
time.sleep(2)
It's the 2nd one I'm having trouble with, currently, with my code, I'm getting the error:
driver.get('https://www.example.com/logon')
AttributeError: 'NoneType' object has no attribute 'get'
I think this is because I'm not connecting the first browser window, instead it's opening a new one which fails with the error above straight away.
Is there possibly a way to keep the first browser open and reuse it? any help would be appreciated.
I'm trying to generate a screenshot for the allure report using the pytest_runtest_makereport hook but get stuck because 'if' statement=false in this block of code:
if 'setup' in item.fixturenames:
web_driver = item.funcargs['setup']
else:
print('Fail to take screenshot.No setup fixture found')
Here is conftest.py:
#pytest.fixture(scope='function')
def get_webdriver(get_edge_options):
options = get_edge_options
print("Current working dir : %s" % os.getcwd())
s = Service('D:\mmanager\msedgedriver.exe')
driver = webdriver.Edge(service=s, options=options)
# driver.delete_all_cookies()
return driver
#pytest.fixture(scope='function') # function means run each test in new browser session
def setup(request, get_webdriver):
driver = get_webdriver
if request.cls is not None:
request.cls.driver = driver
driver.get(FCC_HOME)
yield driver
driver.quit()
# Shared Given Steps
#given('the MM3-0 login page is displayed', target_fixture='MM_Login_page')
def MM_Login_page(setup):
pass
#pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
outcome = yield
rep = outcome.get_result()
if (rep.when == 'call' or rep.when == 'setup') and (rep.failed or rep.skipped):
try:
if 'setup' in item.fixturenames:
web_driver = item.funcargs['setup']
else:
print('Fail to take screenshot.No setup fixture found')
return
allure.attach(
web_driver.get_screenshot_as_png(),
name='!! Screenshot Captured !!',
attachment_type=allure.attachment_type.PNG)
except Exception as e:
print('Fail to take screen-shot: {}'.format(e))
So I wrote this code to get the list of followers on Instagram using instaloader library in python :
login_name = 'beyondhelloworld'
target_profile = 'femindharamshi'
# OR
#import sys
#target_profile = sys.argv[1] # pass in target profile as argument
from instaloader import Instaloader, Profile
loader = Instaloader()
# login
try:
loader.load_session_from_file(login_name)
except FileNotFoundError:
loader.context.log("Session file does not exist yet - Logging in.")
if not loader.context.is_logged_in:
loader.interactive_login(login_name)
loader.save_session_to_file()
profile = Profile.from_username(loader.context, target_profile)
followers = profile.get_followers()
loader.context.log()
loader.context.log('Profile {} has {} followers:'.format(profile.username, profile.followers))
loader.context.log()
for follower in followers:
loader.context.log(follower.username, flush=True)
But I keep getting this error :
Loaded session from /Users/femindharamshi/.config/instaloader/session-beyondhelloworld.
Traceback (most recent call last):
File "/Users/femindharamshi/Documents/instaload/env/lib/python3.7/site-packages/instaloader/structures.py", line 597, in _obtain_metadata
self._node = metadata['entry_data']['ProfilePage'][0]['graphql']['user']
KeyError: 'graphql'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "il.py", line 20, in <module>
profile = Profile.from_username(loader.context, target_profile)
File "/Users/femindharamshi/Documents/instaload/env/lib/python3.7/site-packages/instaloader/structures.py", line 552, in from_username
profile._obtain_metadata() # to raise ProfileNotExistException now in case username is invalid
File "/Users/femindharamshi/Documents/instaload/env/lib/python3.7/site-packages/instaloader/structures.py", line 606, in _obtain_metadata
', '.join(similar_profiles[0:5]))) from err
instaloader.exceptions.ProfileNotExistsException: Profile femindharamshi does not exist.
The most similar profile is: femindharamshi.
How do I solve this issue?
The output says that profile "femindharamshi" does not exist but that is what my profile is. It also says :
The most similar profile is: femindharamshi.
import instaloader
import random
import os
dir_path_driver = os.getcwd()
def username_password():
listusername = []
with open("./username.txt","r") as usernames:
for username in usernames:
listusername.append((username.rstrip("\n")).split(":"))
if len(listusername) == 1:
select = 0
else:
select = random.randint(0,len(listusername))
return listusername[select][0],listusername[select][1]
def get_followers():
L = instaloader.Instaloader()
# Login or load session
username,password =username_password()
listfile = os.listdir(dir_path_driver+"/cookie")
for i in listfile:
if i != f"{username}":
L.login(username, password)
L.save_session_to_file(filename=dir_path_driver+"/cookie/"+f"{username}")
else:
L.load_session_from_file(filename=dir_path_driver+"/cookie/"+f"{username}",username = username)
file = open("prada_followers.txt","a+")
profile = instaloader.Profile.from_username(L.context, "idinstagram")
for followee in profile.get_followers():
username = followee.username
file.write(username + "\n")
file.close()
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
class InstaBot:
"""InstaBot can login, can return unfollowers that don't
follow you back.
Object requires two args.
'Username' & 'Password' """
def __init__(self,username,pw):
self.username = username
self.pw = pw
self.driver = webdriver.Chrome(executable_path='chromedriver.exe')
self.base_url = "https://instagram.com"
self.driver.get("{}".format(self.base_url))
sleep(2)
self.driver.maximize_window()
self.login()
def login(self):
self.driver.find_element_by_xpath("//input[#name=\"username\"]")\
.send_keys(self.username)
self.driver.find_element_by_xpath("//input[#name=\"password\"]")\
.send_keys(self.pw)
self.driver.find_element_by_xpath("//button[#type=\"submit\"]")\
.click()
sleep(10)
self.driver.find_element_by_xpath("//button[contains(text(), 'Not Now')]")\
.click()
sleep(2)
def get_unfollowers(self):
self.driver.find_element_by_xpath("//a[contains(#href, '/{}')]".format(self.username))\
.click()
sleep(3)
self.driver.find_element_by_xpath("//a[contains(#href, '/following')]")\
.click()
sleep(2)
following = self._get_names()
self.driver.find_element_by_xpath("//a[contains(#href, '/followers')]")\
.click()
sleep(2)
followers = self._get_names()
not_following_back = [user for user in following if user not in followers]
return not_following_back
## suggetions = self.driver.find_element_by_xpath('//h4[contains(text(), Suggetions)]')
## self.driver.execute_script('arguments[0].scrollIntoView()',suggetions)
def _get_names(self):
scroll_box = self.driver.find_element_by_xpath("/html/body/div[4]/div/div[2]")
last_ht , ht = 0,1
while last_ht != ht:
last_ht = ht
sleep(1)
ht = self.driver.execute_script("""
arguments[0].scrollTo(0,arguments[0].scrollHeight);
return arguments[0].scrollHeight;
""", scroll_box)
links = scroll_box.find_elements_by_tag_name('a')
names = [name.text for name in links if name.text != '']
sleep(2)
self.driver.find_element_by_xpath("/html/body/div[4]/div/div[1]/div/div[2]/button")\
.click()
return names
def navigate_to_user(self,user):
self.driver.get("{}/{}".format(self.base_url,user))
def scroll_down(self):
last_height = self.driver.execute_script("return document.body.scrollHeight")
while True:
self.driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(2)
new_height = self.driver.execute_script("return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
my_bot = InstaBot(Username,Password)
##unfollowers = my_bot.get_unfollowers() #will return a list
my_bot.navigate_to_user(Any User Name that you follow) #Will return your friend's followers list
I'm beginner in Appium automation,I trying sent messages but have some errors,hope someone help me.
I use "send_keys("0911111111")" it just print into the textbox but can't search and it didn't have search button.
https://imgur.com/a/jo3T0hA
import unittest
from appium import webdriver
from time import sleep
from appium.webdriver.common.touch_action import TouchAction
# Returns abs path relative to this file and not cwd
PATH = lambda p: os.path.abspath(
os.path.join(os.path.dirname(__file__), p)
)
class ContactsAndroidTests(unittest.TestCase):
def setUp(self):
desired_caps = {}
desired_caps['platformName'] = 'Android'
#desired_caps['automationName'] = 'UiAutomator1'
desired_caps['platformVersion'] = '10.0'
desired_caps['udid'] = '8BLAY00DSD'
desired_caps['deviceName'] = 'Pixel 3a'
#desired_caps['app'] = PATH('D:/appium/app/ContactManager.apk')
desired_caps['appPackage'] = 'com.google.android.apps.messaging'
desired_caps['appActivity'] = '.ui.ConversationListActivity'
self.driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', desired_caps)
def tearDown(self):
sleep(1)
self.driver.quit()
def test_text_friend(self):
search_button = self.driver.find_element_by_id("com.google.android.apps.messaging:id/action_zero_state_search").click()
name_search_bar = self.driver.find_element_by_id("com.google.android.apps.messaging:id/zero_state_search_box_auto_complete")
name_search_bar.send_keys("0911111111")
driver.press_keycode(84)
if __name__ == '__main__':
suite =
unittest.TestLoader().loadTestsFromTestCase(ContactsAndroidTests)
unittest.TextTestRunner(verbosity=2).run(suite)