A bit bad in English. I am just making a simple Instagram bot that first takes usernames and passwords from the txt file and put it to login in the website, But "Turn on Notification" pop up only in the first login. Whenever bot login with the second account it does not pop up. I want my WebdriverWait to ignore if it does not find any element. I want it to ignore if "Turn on Notification" does not pop up in other accounts.
My code to remove Turn on Notification pop up:
pop_up = ui.WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".aOOlW.HoLwm"))).click() # Remove notification
sleep(4)
My whole code:
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from getpass import getpass
from selenium.webdriver.support import ui
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# Create a list of username, password pairs from your file.
username_password_list = list()
with open("C:\\Users\\user\\AppData\\Roaming\\JetBrains\\PyCharmCE2020.1\\scratches\\detail.txt") as file:
for line in file:
user, password = line.split(':')
username_password_list.append((user, password))
browser = webdriver.Firefox() # Runs Firefox.
browser.implicitly_wait(5)
browser.get('https://www.instagram.com/') # Web address to load.
for user, password in username_password_list:
class Main:
username_input = browser.find_element_by_css_selector('input[name="username"]') # Finds username field.
password_input = browser.find_element_by_css_selector('input[name="password"]') # Finds password field.
username_input.send_keys(user) # Input username.
password_input.send_keys(password) # Input password.
login_button = browser.find_element_by_xpath('//button[#type="submit"]') # Finds login button.
login_button.click() # Click login button.
pop_up = ui.WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".aOOlW.HoLwm"))).click() # Remove notification.
sleep(4)
class SearchBar:
Search = browser.find_element_by_xpath('//input[contains(#class, "XTCLo x3qfX")]') # Find search bar.
Search.send_keys("Any_Username") # Input.
browser.find_element_by_class_name("yCE8d").click() # Search.
sleep(5)
browser.find_element_by_xpath('//span[#class="vBF20 _1OSdk"]').click() # Finds follow button and click.
sleep(5)
class Logout:
browser.find_element_by_xpath('//*[#id="react-root"]/section/nav/div[2]/div/div/div[3]/div/div[5]').click() # Go to profile.
sleep(5)
browser.find_element_by_xpath('//*[#id="react-root"]/section/main/div/header/section/div[1]/div/button').click() # Click settings.
sleep(5)
browser.find_element_by_xpath('/html/body/div[4]/div/div/div/button[9]').click() # Click logout.
sleep(5)
browser.close()
You can do it with try/except block:
try:
ui.WebDriverWait(browser, 10).until(EC.visibility_of_element_located(
(By.CSS_SELECTOR, ".piCib")))
ui.WebDriverWait(browser, 5).until(EC.element_to_be_clickable(
(By.CSS_SELECTOR, ".aOOlW.HoLwm"))).click()
except:
pass
except block will be executed after a 5-sec timeout when there is no pop-up.
I hope it helps you!
Related
I am working on a project, wherein I am trying to automate the recaptchas. It has been going good so far, however I have run into an issue. Here is the code:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
from selenium import *
from selenium.webdriver import *
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
import requests
def initialize():
options = Options()
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
wait = WebDriverWait(driver, 20)
return driver, wait
def input_info():
name = driver.find_element(By.XPATH, "/html/body/div[3]/div/div/div[1]/form/div[1]/input")
name.send_keys("usernamer12392103821")
password = driver.find_element(By.XPATH, "/html/body/div[3]/div/div/div[1]/form/div[2]/input")
password.send_keys("Password123")
verify_password = driver.find_element(By.XPATH, "/html/body/div[3]/div/div/div[1]/form/div[3]/input")
verify_password.send_keys("Password123")
def select_recaptcha():
men_menu = wait.until(ec.visibility_of_element_located((By.XPATH, "/html/body/div[3]/div/div/div[1]/form/div[7]/div/div/div/iframe")))
men_menu.click()
def get_to_sound():
print("Searching for sound button")
time.sleep(3)
sound_butt_iframe = driver.find_element(By.XPATH, "/html/body/div[5]/div[4]/iframe")
print("Step one complete")
driver.switch_to.frame(sound_butt_iframe)
print("Step two complete")
sound_butt = sound_butt_iframe.find_element(By.XPATH, "/html/body/div/div/div[3]/div[2]/div[1]/div[1]/div[2]/button")
print("Step 4 complete")
driver.switch_to.default_content()
print("Step 5 complete")
sound_butt.click()
### set up driver to go to reddit page!
driver, wait = initialize()
driver.get('https://old.reddit.com/login')
time.sleep(5)
#### Fill in the information necessary! (username, password)
input_info()
time.sleep(3)
print("Finding recaptcha")
select_recaptcha()
print("looking to see if successful!")
try:
successful = wait.until(ec.visibility_of_element_located((By.XPATH, "/html/body/div[5]")))
print("Failed")
print("Call to API with sound file!")
try:
get_to_sound()
except:
print("Failed")
except:
print("Succeeded")
print("Carry on")
time.sleep(10000)
Basically, it will open the https://old.reddit.com/login webpage, enter in a dummy username and password (twice for the confirm) and then click on the recaptcha. This all works great. It realizes that the recaptcha "pops" up, and then it tries to click on the audio button, which is where I run into the problem. I think because it is "stuck" in a new iframe html tag, the XPATH isn't being registered, but I'm not sure. Does someone know how I can get the driver to press the audio control button? I've attached a screenshot below of the html stuff that would be needed for this.
It's the highlighted button tag at the bottom that I am "worried" about
Thanks in advance.
Edit: Here's the picture of the button I am trying to press. I took a picture of the whole recaptcha thing, and the button I am trying to press is the headphones at the bottom.
you should get iframe as element with driver.find_element(By.XPATH), and then find_element(By.XPATH internal) against that element
for that use switch_to_frame method
iframe = driver.find_element_by_xpath("//iframe[#title='...']")
driver.switch_to_frame(iframe)
# here access to internal elements by xpath
driver.find_element(By.XPATH, "")
driver.switch_to.default_content()
If NoSuchElementException accrued and xpath is right then the scroll to target button :
driver.execute_script('arguments[0].scrollIntoView(true);',
driver.find_element_by_xpath(XPATH OF Target button))
I'm trying to write Login credentials using send_keys element method with Selenium on this alert:
Login Alert
I get this alert after clicking on a button in a new window but I can't inspect the elements on this window.
here is my code
import time
import pynput
from selenium import webdriver
driver=webdriver.Chrome("C:/Users/dhias/OneDrive/Bureau/stgg/chromedriver.exe")
driver.get("http://10.15.44.177/control/userimage.html")
time.sleep(3)
window_before = driver.window_handles[0]
driver.maximize_window()
btn=driver.find_element_by_name("TheFormButton3")
btn.click()
window_after = driver.window_handles[1]
driver.switch_to.window(window_after)
obj = driver.switch_to.alert
time.sleep(2)
obj.send_keys('Admin')
time.sleep(2)
I get this error that tells me that there is no alert
I can't acess to the page so I can't try my code but, first I optimized It by adding WebdriverWait and the new By. function:
from selenium import webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = wd.Chrome("C:/Users/dhias/OneDrive/Bureau/stgg/chromedriver.exe")
wait = WebDriverWait(driver, 15)
driver.get("http://10.15.44.177/control/userimage.html")
driver.maximize_window()
window_before = driver.window_handles[0]
wait.until(EC.element_to_be_clickable((By.NAME, "TheFormButton3"))).click()
driver.switch_to.window(driver.window_handles[1])
alert = driver.switch_to.alert
alert.send_keys('Admin\npassword\n') # \n works as an ENTER key
You can try this code to see if the alert really exists or is an element of the webpage:
from selenium.common.exceptions import NoSuchElementException
def is_alert_present(self):
try:
self.driver.switch_to_alert().send_keys('Admin\npassword\n') # \n works as an ENTER key
print('Sucess')
except NoSuchElementException:
print('No Alert Present')
Also see Alerts in the Selenium Documentation
Also Try:
parent_h = browser.current_window_handle
# click on the link that opens a new window
handles = browser.window_handles # before the pop-up window closes
handles.remove(parent_h)
browser.switch_to_window(handles.pop())
# do stuff in the popup
# popup window closes
browser.switch_to_window(parent_h)
# and you're back
So finally I've found a solution..I used the approach where you have to send username and password in URL Request and it worked:
http://username:password#the-site.com
I'm trying to login to Office 365 Outlook using Python Selenium, that redirects for 2 factor Auth.
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
email_ID = "YourEmail#Gmail.com"
Password = "Password"
driver = webdriver.Chrome(executable_path="C:\pythonLibs\chromedriver\chromedriver.exe")
driver.set_page_load_timeout(10)
driver.get("https://outlook.office365.com/mail/inbox")
try:
element = WebDriverWait(driver, 10).until
(
# EC.presence_of_element_located((By.ID, "myDynamicElement"))
EC.url_contains("login.microsoftonline.com/common/oauth2/authorize")
)
finally:
print("2nd Login Page Reached.")
print(driver.current_url)
# Login
driver.find_element_by_id("i0116").send_keys(email_ID)
# driver.find_element_by_id("i0118").send_keys(Password) #passwordBrowserPrefill
print("Login Entered")
driver.find_element_by_xpath('//*[#id="idSIButton9"]').submit()
On the the 1st page redirect (2nd Page) after entering email and submitting, it hits me with a page of
Sign in
Sorry, but we’re having trouble with signing you in.
AADSTS90100: login parameter is empty or not valid.
If I comment out the submit, and click Next manually after email has been entered it works as normal.
I have previously tried adding an implicit wait before submitting, but to no avail
I look forward to your suggestions.
Try:
driver.find_element_by_xpath('//*[#id="idSIButton9"]').click()
Instead of:
driver.find_element_by_xpath('//*[#id="idSIButton9"]').submit()
Because it seems that you're submitting the login form before all the required values are entered.
Creating a script that will log in into the site below and automatically log values into a web form. The problem is that once I login, the landing page is blank (i.e it loads headers but that's it). My code is below:
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
browser = webdriver.Firefox(profile)
browser.get('https://cmsdb.darkcosmos.org/experiments/run/new')
print('Connected to Server')
time.sleep(2) # Wait for page to load
login_button = browser.find_element_by_xpath('/html/body/div/div[5]/main/div/div[1]/div/div[3]/button')
login_button.click()
time.sleep(2) # Wait for pop-out to load
browser.find_element_by_xpath('//*[#id="username"]').send_keys(username)
browser.find_element_by_xpath('//*[#id="password"]').send_keys(password)
login_attempt = browser.find_element_by_xpath('/html/body/div/div[4]/div/div/div/div/div/form/button[1]')
login_attempt.submit()
print('Logged In')
time.sleep(2) # Wait for new page to load
browser.find_element_by_xpath('//*[#id="title"]').send_keys('Title') # Code breaks here. It cannot find the title entry area because the new page is blank.
I've tried making a Firefox profile, giving the page time to load, and turning certificates off. It loads just fine when I manual login. Thanks in advance for the help!
To login within the url https://cmsdb.darkcosmos.org/experiments/run/new and provide the username and password using a new FirefoxProfile you need to induce WebDriverWait for the desired elements to be clickable and you can use the following solution:
Code Block:
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
profile = webdriver.FirefoxProfile()
profile.accept_untrusted_certs = True
browser = webdriver.Firefox(firefox_profile=profile, executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
browser.get('https://cmsdb.darkcosmos.org/experiments/run/new')
print('Connected to Server')
login_button = browser.find_element_by_xpath('/html/body/div/div[5]/main/div/div[1]/div/div[3]/button')
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.v-content__wrap button.v-btn.v-btn--flat.theme--light.primary--text"))).click()
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#username"))).send_keys("clcarver")
browser.find_element_by_css_selector("input#password").send_keys("clcarver")
login_attempt = browser.find_element_by_css_selector("div.v-btn__content>i.v-icon.pr-1.mdi.mdi-lock-open-outline.theme--light").click()
Console Output:
Connected to Server
Browser Screenshot:
I am trying to login into the ESPN footytips website so that I can scrape information for one of my leagues.
I am having no issues opening an instance of Chrome and navigating to the homepage (which contains the login form) and can even select the username field but I cannot for the life of me send my login details to the form.
In debugging I know I can find and select the form submit button and the issue seems to be in passing my login details using send_keys as my exception rule always triggers after I attempt call send_keys.
Any suggestions on how to resolve would be welcomed! My script is below:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
login_address = "http://www.footytips.com.au/home"
me_login = "test#test.com"
me_password = "N0TMYR3#LP#S5W0RD"
browser = webdriver.Chrome()
browser.get(login_address)
try:
login_field = browser.find_element_by_id("ft_username")
password_field = browser.find_element_by_id("ft_password")
print("User login fields found")
login_field.send_keys(me_login)
password_field.send_keys(me_password)
print("Entered login data")
submit_button = browser.find_element_by_id("signin-ft")
print("Submit button found")
submit_button.submit()
except:
print("Error: unable to enter form data")
The locators you have used doesn't uniquely identifies the login_field and the password_field. Additionally you need to wait for the respective WebElements to be visible. Here is your own code with some tweaks :
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
#lines of code
login_address = "http://www.footytips.com.au/home"
me_login = "test#test.com"
me_password = "N0TMYR3#LP#S5W0RD"
browser.get(login_address)
login_field = WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,"//div[#class='login-form']//input[#id='ft_username']")))
password_field = browser.find_element_by_xpath("//div[#class='login-form']//input[#id='ft_password']")
login_field.send_keys(me_login)
password_field.send_keys(me_password)
print("Entered login data")