Python selenium chromedriver instsgram keeps asking for code in sms - python

Has anyone faced the problem that automation routine for instagram written in python with selenium chromedriver has become difficult to run recently because instagram keeps asking for the code it sends in sms or email?
When you do your normal browser login it asks for the code in sms only once. But when you do it with selenium it asks for it every time.
Here is the code
options = webdriver.ChromeOptions()
#options.add_argument('headless')
#options.add_argument('--headless')
options.add_argument('--disable-logging')
options.add_argument('--log-level=3')
driver = webdriver.Chrome(chrome_options=options)
#driver = webdriver.Chrome()
print('Driver started successfully!')
driver.get("https://instagram.com/")
time.sleep(6)
pg=driver.find_element_by_tag_name("html")
lng=pg.get_attribute("lang")
#print(lng)
if lng=='en':
global lin
global foll
global foll_tx
global subscr_tx
lin="Log in"
foll="followers"
foll_tx="Follow"
subscr_tx="following"
get_enter_bt
= driver.find_elements_by_link_text(self.lin)
lin_found=False
while not lin_found:
if len(get_enter_bt)==0:
print('Login not found ((( Refreshing...')
driver.refresh()
time.sleep(6)
get_enter_bt = driver.find_elements_by_link_text(self.lin)
else:
lin_found=True
print('Login button found!')
time.sleep(3)
get_enter_bt[0].click()
time.sleep(3)
#login
login = driver.find_element_by_name("username")
login.send_keys(username)
login = driver.find_element_by_name("password")
login.send_keys(password)
login.send_keys(Keys.RETURN)
time.sleep(9)
get_close_mobapp=driver.find_elements_by_css_selector("button._dbnr9")
if len(get_close_mobapp)!=0:
get_close_mobapp[0].click()
notif_switch=driver.find_elements_by_css_selector("button.aOOlW.HoLwm")
print('notif butt %s' % len(notif_switch))
if len(notif_switch)>0:
notif_switch[0].click()
print(1)
#detect suspicious login
susp_login_msg=driver.find_element_by_xpath("//*[#id=\"react-root\"]/section/div/div/div[1]/div/p")#<p class="O4QwN">Подозрительная попытка входа</p>
print('susm login msg %s' % (susp_login_msg!=None))
if susp_login_msg:
if susp_login_msg.text=='Подозрительная попытка входа':
try:
mobile_button = driver.find_element_by_xpath("//*[#id=\"react-root\"]/section/div/div/div[3]/form/div/div[2]/label")
mobile_button.click()
except:
mobile_button = driver.find_element_by_xpath("//*[#id=\"react-root\"]/section/div/div/div[3]/form/div/div[1]/label")
mobile_button.click()
snd_code_btn=driver.find_element_by_xpath("//*[#id=\"react-root\"]/section/div/div/div[3]/form/span/button")
snd_code_btn.click()
print('Instagram detected an unusual login attempt')
print('A security code was sent to your mobile '+mobile_button.text)
security_code = input('Type the security code here: ')
#security_code_field = driver.find_element_by_xpath(("//input[#id='security_code']"))
security_code_field.send_keys(security_code)
‐----‐‐‐----
This code works fine, but how to stop instagram from asking for the code in sms every time? Does it detect that I run selenium and runs a kind of antibot activity?
I was running the script on schedule to perform series of likes for my subscribers for example which is time consuming you know and automation was my remedy)))

Related

Open whatsapp on a headless browser

Use case:
Sending out automated WhatsApp messages using pythonanywhere. Step by step logic below:
non-coders write on a gsheet the phone numbers to which we should
send out the messages
the gsheet data is read (using gspread in pythonanywhere)
open WhatsApp URL to send out the messages in bulk
I have a code using selenium running on my machine that opens the web whatsapp url, finds the needed elements on the website, and sends the messages to the gsheets phone numbers - find below a snippet from that part of the code that I am using on my machine:
global driver
driver.get('https://web.whatsapp.com/')
waiter.until(EC.title_is("WhatsApp"))
waitCounter = 0
while 1:
try:
waiter.until(EC.presence_of_element_located((By.XPATH, "//canvas[#aria-label='Scan me!']")))
waitCounter+=1
if waitCounter%1000 == 0:
print("Waiting for user to log in...", 'WARNING')
except:
print("Logged in to WhatsApp")
break
for entry in data:
driver.find_element_by_xpath(PHONE_NUMER_INPUT).send_keys(str(entry['PhoneNumber']))
time.sleep(2)
driver.find_element_by_xpath(PHONE_NUMER_INPUT).send_keys(Keys.ENTER)
time.sleep(2)
driver.find_element_by_class_name('p3_M1').send_keys(str(entry['Message']))
time.sleep(2)
driver.find_element_by_class_name('_4sWnG').click()
time.sleep(2)
Doubt:
To make step nr 3. working on python anywhere I would have to use a headless browser. However, to initiate whatsapp web we always need to do the QR code scan, so I am not being able to do it that way. Find below the current (useless) part of my code with the headless selenium code - (NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[#id='side']/div[1]/div/label/div/div[2]"}). I am quite stuck here. Any tip or idea to overcome this is more than welcome and happy to discuss any possible solutions using other libraries that you guys might find appropriate.
Thanks in advance.
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome(options=chrome_options)
def send_whatsapp_message():
global driver
driver.get('https://web.whatsapp.com/')
print("Done updating, check the spreadsheet now")
#redirect('https://web.whatsapp.com/', code=302)
for entry in data:
driver.find_element_by_xpath("//*[#id='side']/div[1]/div/label/div/div[2]").send_keys(str(entry['PhoneNumber']))
time.sleep(2)
driver.find_element_by_xpath("//*[#id='side']/div[1]/div/label/div/div[2]").send_keys(Keys.ENTER)
time.sleep(2)
driver.find_element_by_class_name('p3_M1').send_keys(str(entry['Message']))
time.sleep(2)
driver.find_element_by_class_name('_4sWnG').click()
time.sleep(2)
print("Successfully send message to {0}, name: {1}".format(str(entry['PhoneNumber']), str(entry['Name'])), 'INFO')

twitter bot selenium not liking all tweets on the page

I'm learning about selenium on python and came across an error I don`t really know how to solve:
In this project the bot I've designed was supossed to Like all the tweets on the page when I searched for a certain subject. Altought the bot go through all the loops and like half of the tweets, it still misses every 2 or 3 tweets. Could somebody shed a light on why is it missing tweets?
# it's essencial that the user first pip install selenium on his system or on the source code editor such as visual code
# afterwards download the latest geckodriver on github and unzip it on the root of your python folder
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
class TwitterBot:
def __init__(self,username,password):
self.username = username
self.password = password
self.bot = webdriver.Firefox()
def login(self):
bot = self.bot
bot.get('https://twitter.com/login')
time.sleep(5) # I used a timer to load wait for the page to load before entering the login and password
email = bot.find_element_by_name("session[username_or_email]")
password = bot.find_element_by_name("session[password]")
email.clear()
password.clear()
email.send_keys(self.username)
password.send_keys(self.password)
password.send_keys(Keys.RETURN)
time.sleep(5)
def like_tweet(self,hashtag):
bot = self.bot
bot.get('https://twitter.com/search?q='+hashtag+'&src=typeahead_click')
time.sleep(3)
bot.find_element_by_link_text("Latest").click()
time.sleep(3)
for i in range(6):
bot.execute_script('window.scrollTo(0,document.body.scrollHeight)')
time.sleep(3)
tweets = bot.find_elements_by_xpath('//div[#data-testid="tweet"]')
for tweet in tweets:
try:
bot.find_element_by_xpath('//div[#data-testid="like"]').click()
time.sleep(3)
except:
print("ERROR")
bot = TwitterBot('xxx#gmail.com','xxxxx') # Enter here your username/e-mail and password like this: ('email#email.com','password')
bot.login()
bot.like_tweet('python learning') # Enter here the subject you want the bot to search for ('subject')

Selenium submit button element not interactable

I posted recently about some trouble I was having with selenium, primarily the anticaptcha API. Ive managed to solve that but I am having some trouble over here. This is my current code:
from time import sleep
from selenium import webdriver
from python_anticaptcha import AnticaptchaClient, NoCaptchaTaskProxylessTask
import os
import time
#Gather Api Key
api_key = 'INSERT API KEY HERE'
#Go to the acc registration site
browser = webdriver.Chrome()
browser.implicitly_wait(5)
browser.get('https://www.reddit.com/register/')
sleep(2)
#Input email
email_input = browser.find_element_by_css_selector("input[name='email']")
email_input.send_keys("INSERT EMAIL HERE")
#Continue to the next part of the registration process
continue_button = browser.find_element_by_xpath("//button[#type='submit']")
continue_button.click()
#Find and input the username and password fields
username_input = browser.find_element_by_css_selector("input[name='username']")
password_input = browser.find_element_by_css_selector("input[name='password']")
username_input.send_keys("INSERT USERNAME HERE")
password_input.send_keys("INSERT PASSWORD HERE")
#Gather site key
url = browser.current_url
site_key = "6LeTnxkTAAAAAN9QEuDZRpn90WwKk_R1TRW_g-JC"
#Acc do the solving process
client = AnticaptchaClient(api_key)
task = NoCaptchaTaskProxylessTask(url, site_key)
job = client.createTask(task)
print("Waiting for recaptcha solution")
job.join()
# Receive response
response = job.get_solution_response()
print(response)
print("Solution has been gotted")
# Inject response in webpage
browser.execute_script('document.getElementById("g-recaptcha-response").innerHTML = "%s"' % (response))
print("Injecting Solution")
# Wait a moment to execute the script (just in case).
time.sleep(1)
print("Solution has been gotted for sure")
# Press submit button
browser.implicitly_wait(10)
Signup = browser.find_element_by_xpath('//input[#type="submit"]')
Signup.click()
Everything runs smoothly except for the final line. I think the program is recognizing the submit button but for some reason gives an element not interactable error. Any help on how to solve this would be greatly appreciated
I had the same issue when I was using selenium. Sometimes it happens that even though selenium has recognized the element, its function is not "ready." Adding a delay before clicking the submit button should fix the issue.

How to use python to create account on a website?

I am developing a website that works with Asana, so when a new user registers on my website, they should also be automatically registered on Asana as well.
How can I use python to register a new account on Asana based on the email and password provided on the sign up page of my site?
https://asana.com/
I found the script someone posted for sign up facebook, can it be used to sign up on Asana? "usr" "pwd" should be the input on my website.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from time import sleep
usr=input('Enter Email Id:')
pwd=input('Enter Password:')
driver = webdriver.Chrome()
driver.get('https://www.facebook.com/')
print ("Opened facebook...")
sleep(1)
a = driver.find_element_by_id('email')
a.send_keys(usr)
print ("Email Id entered...")
sleep(1)
b = driver.find_element_by_id('pass')
b.send_keys(pwd)
print ("Password entered...")
c = driver.find_element_by_id('loginbutton')
c.click()
print ("Done...")
sleep(10)
driver.quit()

Cannot contact reCAPTCHA. Check your connection and try again in selenium with python

I want to make a python program that gets all links for a certain Google search query so I loop over the 30 search pages and when it gives me a ReCaptcha I do it manually
here is how my code looks like :
driver = webdriver.Firefox()
number_pages = 30
query = 'hello world'
query = urllib.parse.quote_plus(query)
url = "https://www.google.com/search?q="+query+"&&start="
with open('result.txt','w') as fp:
for i in range(1,number_pages-1):
# loop over the 30 pages
page_url = url + str((i-1)*10)
print("# " + page_url)
driver.get(page_url)
while len(driver.find_elements_by_id('recaptcha')) != 0:
# ReCaptcha , sleeping until the user solve the recaptcha
print('sleeping...!')
time.sleep(10)
els = driver.find_elements_by_tag_name('cite')
But when i try to send the recaptcha form it gaves me the error:
Cannot contact reCAPTCHA. Check your connection and try again
and when I use a normal navigator (Google Chrome or Firefox ) the error don't occur
I think the ReCaptcha blocks the webdriver
Please anyone can explain what exact issue here, and how can be fixed.

Categories