Script is not running after comment in my code using selenium python - python

I am trying to automate Linked in using selenium.
I want to search Journalist and wants to connect them all.
So, I wrote the code that click all the connect buttons.
but it is not working.
from selenium import webdriver
import time
driver = webdriver.Chrome('C:\\Users\\SUJASH\\AppData\\Local\\Temp\\HZ$D.705.3782\\HZ$D.705.3783\\chromedriver.exe')
driver.get('https://www.linkedin.com')
time.sleep(2)
#********** LOG IN *************
username = driver.find_element("id", "session_key")
password = driver.find_element("id", "session_password")
#above code will find the box of Username and Password
username.send_keys('HIDDEN_ON_SOF')
password.send_keys('HIDDEN_ON_SOF')
time.sleep(2)
#above code will enter the username and Password
submit = driver.find_element("xpath", "//button[#type='submit']").click()
#above code will click the submit button
#*********** SEARCH ***********
driver.get('https://www.linkedin.com/search/results/people/?heroEntityKey=urn%3Ali%3Aautocomplete%3A1975299068&keywords=entertainment%20journalist&origin=CLUSTER_EXPANSION&sid=uv!')
time.sleep(5)
'''above code has link of my search that I want to do, I want to search Entertainment journalist, so I searched Entertainmnet journalist and copy the link and pasted it here'''
#************ from here script is not working ****************************
all_buttons = driver.find_elements("tag_name", "button")
connect_buttons = [btn for btn in all_buttons if btn.text == "Connect"]
for btn in connect_buttons:
driver.execute_script("arguments[0].click();", btn)
time.sleep(2)
send = driver.find_element("xpath" , "//button[#aria-label='Send now']")
driver.execute_script("arguments[0].click();", send)
close = driver.find_element("xpath" , "//button[#aria-label='Dismiss']")
driver.execute_script("arguments[0].click();", close)
time.sleep(2)
''' Above code is not working, I want to click on all the connect buttons but code is not working after the comment *** from here script is not working *** '''

Related

Python - Pop up window authentication without a source code

i'm trying to access a pop-up authentication box in a internal link which i can t share as it is confidential, i tried the below code to access it, it works fine for a single link but i have multiple links which i have it under a loop.
driver.get(links[i])
time.sleep(2)
window_before = driver.window_handles[0]
driver.switch_to.window(window_before)
shell = win32.Dispatch("WScript.Shell")
time.sleep(2)
shell.Sendkeys('username')
shell.Sendkeys('{TAB}')
shell.Sendkeys('password')
shell.Sendkeys('{ENTER}')
time.sleep(4)
#Second login page Enter password again and log in
password = driver.find_element_by_name('p_t02').send_keys('password')
logon = driver.find_element_by_xpath("//td[#class='t10C']").click()
Problem: when it runs the second loop for the second link it actually skips to the below part and throws an error
driver.get(links[i])
time.sleep(2)
window_before = driver.window_handles[0]
driver.switch_to.window(window_before)
shell = win32.Dispatch("WScript.Shell")
time.sleep(2)
shell.Sendkeys('username')
shell.Sendkeys('{TAB}')
shell.Sendkeys('password')
shell.Sendkeys('{ENTER}')
time.sleep(4)
it skips the above and goes to the below code and throws an error
#Second login page Enter password again and log in
password = driver.find_element_by_name('p_t02').send_keys('password')
can anyone help me get past the authentication with another way
like without using the
shell = win32.Dispatch("WScript.Shell")

Task done in python automation

Like the title says I am working on a little project where I need to
"open link, click on a button, replace a part of the link and do the task again"
My code is a little messy and I am still a newbie, but this is it so far, and the problem I am running into is that the page doesn't open when I add the 'if else' function. The page just doesn't open, I could do without the if else, but since the button's xpath changes in random numbered pages that's the only solution I can think of
PATH = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=PATH)
driver.maximize_window()
button = driver.find_element_by_xpath("/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div[2]/div[3]/div/div[2]/button")
button1 = driver.find_element_by_xpath("/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div/div[3]/div/button")
for i in range(1,5):
print(f"https://test.com/page/{i}")
driver.get(f"https://test.com/page/{i}")
if button is not None:
button.click()
else:
button1.click()
Load the page before getting the buttons. Also, make sure the button is loaded with this script:
PATH = Service("C:\Program Files (x86)\chromedriver.exe")
driver = webdriver.Chrome(service=PATH)
driver.maximize_window()
button_selector = "/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div[2]/div[3]/div/div[2]/button"
button1_selector = "/html/body/div[1]/div[1]/main/div/div/div/div[1]/div/div[1]/div[2]/div[1]/div/section/div/div[3]/div/button"
for i in range(1, 5):
print(f"https://test.com/page/{i}")
# Load the page
driver.get(f"https://test.com/page/{i}")
# Get the buttons
button = driver.find_element_by_xpath(button_selector) or None
button1 = driver.find_element_by_xpath(button1_selector) or None
time.sleep(1) # Make sure the buttons are loaded
if button is not None:
button.click()
elif button1 is not None:
button1.click()
driver.quit() # Be sure to close the driver

Log in to instagram using selenium

I am a novice coder. Trying my hand at creating an instagram bot and I'm following the instructions found here: (https://realpython.com/instagram-bot-python-instapy/)
I can fill in the elements for user name and password, but I'm having trouble clicking the login link. Using the -
#submit = browser.find_element_by_tag_name('form')
#submit.submit()
portion of my code works to log in, but I would like to be able to use find element by xpath and for this so I can apply it in different situations. If someone could please let me know where I can look in the HTML on the instagram page to find what I'm looking for, or direct me towards any helpful reading, I'd really appreciate it! I've tried a few ways to do this.
Here is my code. I also added photos of my code and error message.
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#sets browser to firefox - need to make sure that geckodriver and firefox are in the path
browser = webdriver.Firefox()
#opens firefox to instagram#
browser.get('https://www.instagram.com/accounts/login/?source=auth_switcher')
#tells selenium to wait 5 seconds before trying again if it can't find something
browser.implicitly_wait(10)
print ('i waited')
user = 'username'
password = 'password'
##### USERNAME #####
username = browser.find_element_by_xpath("//input[#name='username']")
username.send_keys(user)
#username = browser.find_element_by_name('username')
#username.send_keys(user)
##### PASSWORD #####
password = browser.find_element_by_xpath("//input[#name='password']")
password.send_keys(password)
#password = browser.find_element_by_name('password')
#password.send_keys(password)
browser.implicitly_wait(10)
##### LOG IN #####
#instead of searching for the Button (Log In) you can simply press enter when you already selected the password or the username input element.
#submit = browser.find_element_by_tag_name('form')
#submit.submit()
#login_link = browser.find_element_by_xpath("//article/div/div/p/a[text()='Log in']")
login_link = browser.find_element_by_xpath("//a[text()='Log in']")
login_link.click()
#login_form = browser.find_element_by_xpath("//form[#id='loginForm']")
#form.submit()
print ('login incomplete :)')
sleep(5)
browser.quit() #quits geckodriver and mozilla
print ('closed')
Picture of error
code part 1
code part 2
Your xpath is bit wrong. you are using
//a[text()='Log in']
but Log in is inside div tag, not a tag.
Please use this xpath
//div[text()='Log In']/..
In your code
login_link = browser.find_element_by_xpath("//div[text()='Log In']/..")
login_link.click()
The HTML is
<div class=" qF0y9 Igw0E IwRSH eGOV_ _4EzTm ">Log In</div>
and we are using text() to target text Log in and then we are looking for button using /.. which is a parent node.
Replace this link
login_link = browser.find_element_by_xpath("//a[text()='Log in']")
with
login_link = browser.find_element_by_xpath("//div[contains(text(),'Log In')]")
And you should be good. Since the Login In button is wrapped inside a div element and not a element.
As already explained Log In is in a div tag under a button tag with type submit. You can use this xpath too.
browser.find_element_by_xpath("//button[#type='submit']").click()

While automating Whatsapp my code types the message multiple times without sending it while it is supposed to type it once and send it in a loop

from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://web.whatsapp.com/')
name = str(input("enter the name of the group:"))
msg = str(input("enter teh message:"))
count = int(input("enter the count:"))
input("enter anything after scanning the qr code")
user = driver.find_element_by_xpath('//span[#title= "{}"]'.format(name))
user.click()
msg_box= driver.find_element_by_class_name('_3uMse')
for i in range(count):
msg_box.send_keys(msg)
button = driver.find_element_by_class_name('_1JNuk')
button.click()
and when i give it to write "lo" for 50 times it does this as given in the image
how can i click the send button everytime after typing the input
SOORY!!if the question is too messy im just a noob programmer!!
if that send button click is not working ,you can try below options,
Option 1-Instead of click on send button if we just press enter the
message will send
msg_box.send_keys(msg+ Keys.ENTER)
Option 2- Assuming your xpath is correct,you also try to click on send button using javascriptexecutor
button = driver.find_element_by_class_name('_1JNuk')
driver.execute_script("arguments[0].click();", button)

How to login to a website properly with Python Selenium webdriver?

I am trying to log in to my amboss account using Selenium webdriver with python, but as I dont have much experience with it I dont understand what goes wrong. My credentials (email and password) are correct as I have used them to log into the website before.
Here is my code so far:
# run firefox webdriver from executable path
driver = webdriver.Firefox(firefox_options=options, capabilities=cap, executable_path = path_to_driver)
driver.get("https://www.amboss.com/us/account/login")
signinusername = config['amboss']['email']
signinpassword= config['amboss']['password']
username = driver.find_element_by_id("signin_username")
username.clear()
username.send_keys(signinusername)
pwd = driver.find_element_by_xpath("//*[#id='signin_username']")
pwd.clear()
pwd.send_keys(signinpassword)
loginbutton = driver.find_element_by_xpath("/html/body/div[2]/div[1]/div/div/form/div[4]/input").click()
time.sleep(20)
# execute script to scroll down the page
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
#element in log in page
newelement = driver.find_element_by_xpath("//*[#id='left']/p[1]/strong")
print(newelement.get_attribute('innerHTML'))
What I try to do here is log in to the platform and then grab an element which I see in the welcome page by xpath. Despite that selenium is unable to find this element and I get the following error:
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: //*[#id='left']/p[1]/strong
Does anyone understand why this happens? Is it because log in was not successful or could something else be wrong? Thanks in advance
UPDATE
The elements you were trying to fetch were in an iframe so you need to switch to that iframe so they be visible. The following works, try it.
username = driver.find_element_by_id("signin_username")
username.clear()
username.send_keys(signinusername)
pwd = driver.find_element_by_id('signin_password')
pwd.clear()
pwd.send_keys(signinpassword)
loginbutton = driver.find_element_by_class_name('amboss-button').click()
time.sleep(2)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);var lenOfPage=document.body.scrollHeight;return lenOfPage;")
time.sleep(2)
frames = driver.find_elements_by_tag_name('iframe')
driver.switch_to.frame(frames[4])
newelement = driver.find_elements_by_tag_name('p')[0].text # This prints the following 'You now have access to AMBOSS—an all-in-one pl....'
print(newelement)
I'm assuming you're trying to login to the system and trying to find something.
First of all your login attempt is not correct. You're entering password in the username field in your code.
Please do login like this:
At first, add this import to your python script:
from selenium.webdriver.common.keys import Keys
Then do login like this:
username = driver.find_element_by_id("signin_username")
username.clear()
username.send_keys(signinusername)
pwd = driver.find_element_by_id("signin_password")
pwd.clear()
pwd.send_keys(signinpassword)
pwd.send_keys(Keys.ENTER)
I'm not logging in by clicking the button. Just hitting an ENTER after logging in.
I guess correcting the login attempt will help you to find your element and print contents inside this.
I've created an account in amboss to answer your question and after logging in the only iframe I found was from google tag manager with no contents in it. So I'm not really sure if your account contains some other web views.
Hope correcting the login attempt helps.
First you wrong this is line :
pwd = driver.find_element_by_xpath("//*[#id='signin_username']")
Please change with :
pwd = driver.find_element_by_id('signin_password')
Second, use conditional if for validation success or failed login :
click login here
time.sleep(20)#here recommendation use WebDriverWait
count = len(driver.find_elements_by_xpath("//*[#id='left']/p[1]/strong"))
if count > 0:
print("login success")
print(driver.find_element_by_xpath("//*[#id='left']/p[1]/strong").text)
else:
print("login failed")
Make sure this is the correct locator : //*[#id='left']/p[1]/strong

Categories

Resources