I'm trying to create a script for loop from the CSV file to filling up the website email and password.
But the loop is only stuck at the first ROW, can't go to the next ROW. Anyone can help?
Open Browser
Go to a website
Auto Log-in (filling up email and password details from csv file )
Close Browser
Re open again the website(loop start from the second step )
Re Auto log-in but with the second account (filling up details from csv file SECOND ROW ) .
Re do the same tasks 50 times (From account 1 to 50 for example )
I am running Python 3.8.1 and PyCharm.
import pandas as pd
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome = webdriver.Chrome(options=chrome_options)
chrome.get("https://facebook.com")
data = pd.read_csv(r'D:\PyCharm\test.csv')
df = pd.DataFrame(data)
i = 0
while i == 0:
a = 0
Username = df.username
Password = df.password
id_box = chrome.find_element_by_id('email')
id_box.send_keys(Username[a])
Pass_box = chrome.find_element_by_id('pass')
Pass_box.send_keys(Password[a])
Send = chrome.find_element_by_name('login')
Send.click()
try:
test = chrome.find_element_by_id('pass')
id_box.clear()
Pass_box.clear()
except:
print("logged in")
break
a = a + 1
Related
i tried to create a threading to login with a lot of usage, using python Threading, but I got a little error, my code can't handle the following task, I have 10 users, and run threading with threading, python code stops after 2 user logins, and the rest cannot be called, some code please add to fix this problem
python
print (variable)
import threading
from selenium import webdriver
import time
import numpy as np
from csv import reader
def Login_browser(i):
id_str = ids_pass_list[i][0]
id_pass = ids_pass_list[i][1]
print(i)
print("Login Id: ", id_str)
print("Login Password: ", id_pass)
Options = webdriver.ChromeOptions()
Options.add_argument('--app-https://google.com')
driver = webdriver.Chrome(options=Options)
driver.get('http://localhost/login2/index.php')
time.sleep(1)
try:
driver.get('http://localhost/login2/index.php')
time.sleep(1)
email_field = driver.find_element_by_name("userid")
email_field.send_keys(id_str)
time.sleep(3)
password_field = driver.find_element_by_name("pass")
password_field.send_keys(id_pass)
time.sleep(3)
submit = driver.find_element_by_xpath("/html/body/center/form/table/tbody/tr[3]/td/button[1]")
submit.click()
time.sleep(30)
driver.quit()
except:
time.sleep(10)
Page_Thread = 2
threads = []
with open('user.csv', 'r') as read_obj:
csv_reader = reader(read_obj)
list_of_rows = list(csv_reader)
total_Len = len(list_of_rows)
ids_pass_list = list_of_rows
for i in range(Page_Thread):
threads += [threading.Thread(target=Login_browser,args={i},)]
for t in threads:
t.start()
for t in threads:
t.join
print ( 'succses')
This is the code:
#A simple Kahoot bot that joins Kahoot game and sits idle
#Version 1.4.4
#ENTech SS
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
import random
#Asking for info here:
print("Kahoot spammer v 1.4.4")
pin = input("Please enter a game pin:")
name = input("Please enter a name:")
join = input("Please enter a amount of bots to join(Default is 50):")
tab = 0
nameb = str(name)
bot_num = 0
#Start chrome
print("Starting chrome...")
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(executable_path="/Users/adamkatborg/Desktop/chromedriver-2", options="options")
#driver = webdriver.Chrome(chrome_options=chrome_options)
#If join feild is blank, then default is 50
if join=='':
join=50
def namec():
#Code for clarifying name
global join, bot_num, nameb
num=random.randint(1,999)*3
if join=='1':
nameb=name
bot_num = bot_num + 1
if int(join)>=2:
if bot_num==join:
print("Name generation completed")
nameb=(name + '.' + str(num))
bot_num = bot_num + 1
def bot():
global nameb, driver, tab
if bot_num==1:
print("No new window necessary")
elif bot_num >=2:
print("Opening new window...")
driver.execute_script("window.open('');")
driver.switch_to.window(driver.window_handles[tab])
print("Navigating to Kahoot...")
#Navigate to kahoot.com
driver.get("https://kahoot.it/")
#Wait untill element is available
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'inputSession')))
#Finding input box
inputb = driver.find_element_by_id('inputSession')
print("Joining game...")
#Inputting pin
inputb.send_keys(pin)
inputb.submit()
#Entering name
element = wait.until(EC.element_to_be_clickable((By.ID, 'username')))
gname = driver.find_element_by_id('username')
namec()
gname.send_keys(nameb)
gname.submit()
#Checking login
print("Checking if login was succesfull...")
try:
content = driver.find_element_by_class_name('ng-binding')
except:
print("Error checking page:\nId could have changed, or connection could have dropped.")
x=input("Press any key to exit...")
print("Success!")
print("Bot [" + bot_num + "] is now in the game ;)")
tab = tab + 1
#Code for running a set amoun of times
for x in range(int(join)):
bot()
And this is the error I am getting:
Traceback (most recent call last):
File "/Users/adamkatborg/Desktop/kbot-master/testbot.py", line 23, in <module>
driver = webdriver.Chrome(executable_path="/Users/adamkatborg/Desktop/chromedriver-2", options="options")
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py", line 64, in __init__
desired_capabilities = options.to_capabilities()
AttributeError: 'str' object has no attribute 'to_capabilities'
Can someone please help me?
On line 23 you are passing "options" as the options parameter, it looks like it is expecting an object instead of a string.
What you probably meant to do was pass the chrome_options object. The line should look like this:
driver = webdriver.Chrome(executable_path="/Users/adamkatborg/Desktop/chromedriver-2", options=chrome_options)
I want to send whatsapp using selenium python
Im getting my contact numbers from a csv file
So
With a loop
Im typing phone numbers in contact search box (WhatsApp web)
(Because that some of my phone contact are duplicate so I'm using their phone in search box instead of their name)
And entering Enter button (off course with selenium)
And with that it's entering the only result chat
So i can send the message and etc.
The problem is that when there is no result in searching number it's sending the messages to the last person that was sent to
So the last person gets duplicate message
How can i determine if the search is giving me any result
Or in this case
How can i know if the number has whatsapp or not
Thanks
from selenium import webdriver
import time
import pandas as pd
import os
import xlrd
import autoit
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
fileName = 'test.csv'
messages_excel = 'messages.xlsx'
driver = webdriver.Chrome('D:\python\chromedriver')
driver.get('https://web.whatsapp.com/')
input('after QR Code')
with open(fileName) as file:
data = pd.read_csv(file)
df = pd.DataFrame(data)
msgdata = pd.read_excel(messages_excel, sheet_name=r'Sheet1')
for index, row in df.iterrows():
try:
search_phone = int(row['phone'])
search_box = driver.find_element_by_class_name('_2zCfw')
search_box.send_keys(search_phone)
time.sleep(2)
search_box.send_keys(u'\ue007')
for i in msgdata.index:
try:
clipButton = driver.find_element_by_xpath('//*[#id="main"]/header/div[3]/div/div[2]/div/span')
clipButton.click()
time.sleep(1)
# To send Videos and Images.
mediaButton = driver.find_element_by_xpath(
'//*[#id="main"]/header/div[3]/div/div[2]/span/div/div/ul/li[1]/button')
mediaButton.click()
time.sleep(3)
image_path = os.getcwd() + "\\Media\\" + msgdata['photoName'][i]+'.jpg'
autoit.control_focus("Open", "Edit1")
autoit.control_set_text("Open", "Edit1", (image_path))
autoit.control_click("Open", "Button1")
time.sleep(1)
previewMsg = driver.find_element_by_class_name("_3u328").send_keys(u'\ue007')
time.sleep(3)
productName = str(msgdata['name'][i])
oldPrice = str(msgdata['oldqimat'][i])
newPrice = str(msgdata['newqimat'][i])
inventory = str(msgdata['inventory'][i])
msg_box = driver.find_element_by_xpath('//*[#id="main"]/footer/div[1]/div[2]/div/div[2]')
msg_box.send_keys("stocks")
msg_box.send_keys(Keys.SHIFT + '\ue007')
msg_box.send_keys(productName)
msg_box.send_keys(Keys.SHIFT + '\ue007')
if oldPrice != 'nan':
msg_box.send_keys("oldPrice : "+ oldPrice)
msg_box.send_keys(Keys.SHIFT + '\ue007')
if newPrice != 'nan':
msg_box.send_keys("newPrice : "+ newPrice)
msg_box.send_keys(Keys.SHIFT + '\ue007')
if inventory!= 'nan':
msg_box.send_keys("inventory : "+ inventory)
time.sleep(1)
msg_box.send_keys(Keys.ENTER)
time.sleep(3)
except NoSuchElementException:
continue
except NoSuchElementException:
continue
print("sucessfully Done")
when there is no result in searching number it's sending the messages to the last person that was sent to So the last person gets duplicate message
Im getting my contact numbers from a csv file So With a loop Im typing phone numbers in contact search box (WhatsApp web)
You could store the last # you contacted as a variable and check if the current recipient of the message, matches the stored contact #.
A simple If/Else should do the trick.
Code
last_contacted = None
for index, row in df.iterrows():
try:
if row['phone'] == last_contacted:
print("number already contacted")
next
else:
search_phone = int(row['phone'])
last_contacted = search_phone
print(search_phone)
After you fill the search contact box string and send the Enter key, the “best match” contact name will be displayed at top of the right message panel.
Inspect that element and make sure it matches your search before continuing.
I am new to python and I need help with web scraping code to save a dynamic map every week.
This is the site I am interested in.
The purpose is to get to the page, select season, select week, and download image to a local folder. I'll use the image to integrate for an automated weekly report using SAS.
thank you in advance!
import sys
import os
import time
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium import webdriver
import arrow
BASE_URL = 'https://gis.cdc.gov/grasp/fluview/main.html'
DOWNLOAD_PATH = "/Users/"
def closeWebDriver(driver):
if os.name == 'nt':
driver.quit()
else:
driver.close()
def getImage():
profile = FirefoxProfile()
profile.set_preference("browser.download.panel.shown", False)
profile.set_preference("browser.helperApps.neverAsk.openFile","image/png")
profile.set_preference("browser.helperApps.neverAsk.saveToDisk", "image/png")
profile.set_preference("browser.download.folderList", 2);
profile.set_preference("browser.download.dir", DOWNLOAD_PATH)
driver = webdriver.Firefox(firefox_profile=profile)
driver.get(BASE_URL)
time.sleep(5)
if not isValidTimeFrame(driver):
print('Not the time to download yet!')
closeWebDriver(driver)
return
selectFirstWeek(driver)
print('- Consume the web.')
wrapper = driver.find_element_by_class_name('downloads-help-area')
download_img_els = wrapper.find_elements_by_class_name('downloads-button')
for el in download_img_els:
text = el.text.encode('utf-8')
# print(text)
if 'download image' == text.strip().lower():
# Process
downloadImage(el)
break
time.sleep(5)
closeWebDriver(driver)
def isValidTimeFrame(driver):
seasons_button = driver.find_element_by_class_name('seasons-button')
time_frame = seasons_button.text.encode('utf-8').strip().lower()
current_year = arrow.now().to('local')
current_year_str = current_year.format('YYYY')
next_year = current_year.shift(years=1)
next_year_str = next_year.format('YY')
print(time_frame)
compare_year = '%s-%s' % (current_year_str, next_year_str)
return time_frame == compare_year
def selectFirstWeek(driver):
prev = driver.find_element_by_id('prevMap')
week = driver.find_element_by_id('weekSlider')
while True:
print(week)
current_number = week.get_property('value')
print('- Week: ' + current_number)
prev.click()
if int(current_number) < 2:
break;
time.sleep(1)
def downloadImage(el):
print('- Click on ' + el.text)
el.click()
getImage()
I made a program which gets one record from Google Sheet process on it then delete it and so on. If I update Google Sheet then the program will deduct record in the next loop and process on it and then delete,
but it runs only 1 or 2 hours and then program gives an error:
What can I add in my program so my program never stops?
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import traceback
import string
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import UnexpectedAlertPresentException
Email=raw_input('Please Enter your Email: ')
password=raw_input('Please Enter Password: ')
print("\n******Don't Interrupt the Script******")
print('#script is Runing............\n')
chrome_options = webdriver.ChromeOptions() #going to chrome options
chrome_options.add_argument("--start-maximized")
prefs = {"profile.default_content_setting_values.notifications" : 2 #turn off all notifications
,"profile.managed_default_content_settings.images": 2} #disable images
chrome_options.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chrome_options) # passing paramaters to chrome
driver.get('https://accounts.google.com')
time.sleep(3)
#giving Email-------------------
email = driver.find_element_by_id('Email')
email.send_keys(Email, Keys.RETURN)
#giving password----------------
time.sleep(3)
email = driver.find_element_by_id('Passwd')
email.send_keys(password, Keys.RETURN)
#credentials + attach with googleSheet------------------------------
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name('stephens-31d8490b5bd2.json', scope)
google_sheet = gspread.authorize(credentials)
workSheet = google_sheet.open("Video Access Master Sheet").worksheet("Sheet1")
while True:
#fetch Records from Rows 2 to 50 and save on list-----------------
for i in range(2,51):
li_url=[]
li_email=[]
row=workSheet.row_values(i)
for b in row:
if 'youtu' in b:
li_url.append(b)
#find record which you append on list and then delete from googleSheet--------------------
cell = workSheet.find(b)
row = cell.row
col = cell.col
workSheet.update_cell(row,col, '')
print 'Fetching Values From Row '+str(i)+'....'
elif '#' in b:
li_email.append(b)
elif b=='':
continue
else:
continue
#*********************************************************
#getting length list of li_url and apply condition on it-----------------------------------------------
length=len(li_url)
if length==0:
continue
else:
try:
#getting URLs from list and put into driver.get---------------------------------------------------------
for a in li_url:
driver.get(a)
time.sleep(3)
driver.find_element_by_css_selector('.yt-uix-button-icon.yt-uix-button-icon-info.yt-sprite').click()
time.sleep(3)
driver.find_element_by_css_selector('.yt-uix-button.yt-uix-button-size-default.yt-uix-button-default.metadata-share-button').click()
time.sleep(2)
put_email=driver.find_element_by_css_selector('.yt-uix-form-input-textarea.metadata-share-contacts')
#getting emails from email list--------------------------------------------------------------
put_email.send_keys(li_email[0])
time.sleep(2)
driver.find_element_by_css_selector('.yt-uix-button.yt-uix-button-size-default.yt-uix-button-primary.sharing-dialog-button.sharing-dialog-ok').click()
time.sleep(4)
driver.find_element_by_xpath('.//*[#id="video-header"]/div/button[2]/span').click()
time.sleep(10)
#for notifications and alters--------------------------------------------
try:
driver.switch_to.alert.accept()
except NoAlertPresentException:
pass
except UnexpectedAlertPresentException:
pass
except:
traceback.print_exc
pass
print 'Row '+str(i)+' Successfully Updated. \n'
time.sleep(120) #while loop sleep for 20minuts
This is the error I got:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "<string>", line 56, in parse
File "<string>", line 35, in parse
cElementTree.ParseError: no element found: line 1, column 0
For some reason cell = workSheet.find(b) fails. Could be bad data in there; without seeing the input it's anyone's guess.
Since you already know the row number, you can avoid using cell = workSheet.find(b) by simply keeping track of the columns you're searching through and finally calling workSheet.update_cell(i, col, '') after copying the data.