selenium scrolling after click unclicks - python

Updated selenium script with opensource autoliker, i will post social network, username and password because it hard to understan what happens real life, edited some code scrolls still same result only first post liked.
only thing i want is to click like button on
a.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
and keep scroling, each like button has same atribute
social network hiall.app
username -whatl0ol
password - tornike123
trying to update source, will post results
source code
from selenium import webdriver
from selenium.common import exceptions
from selenium.webdriver.chrome.options import Options
class FacebookBot:
def __init__(self,username,password,status_report=False):
self.username = username
self.password = password
self.status_report = status_report
options = Options()
options.add_argument("--disable-notifications")
if self.status_report: print("Opening chromedriver...")
self.wd = webdriver.Chrome(chrome_options=options)
if self.status_report: print("Logging in...")
self.login()
def login(self):
self.wd.get("https://hiall.app")
self.wd.find_element_by_name("username").send_keys(self.username)
self.wd.find_element_by_name("password").send_keys(self.password)
self.wd.find_element_by_css_selector("button.btn.btn-main").click()
def convert_to_int(self,string):
try:
return int(string)
except ValueError:
if string.lower().endswith("k"):
string = string[:-2]
try:
return int(float(string)*1000)
except ValueError:
return int(string)*1000
def get_posts(self):
articles = self.wd.find_elements_by_css_selector("span#like-button.btn.btn-default.stat-item")
data = []
for a in articles:
if a.get_attribute("id").startswith("span#like-button.btn.btn-default.stat-item"):
likeIts = [i.get_attribute("aria-label").split() for i in a.find_elements_by_css_selector("span#like-button.btn.btn-default.stat-item") if i.get_attribute("aria-label")]
likes = {"Like":0,"Love":0,"Haha":0,"Wow":0,"Sad":0,"Angry":0}
likes.update({i[1]: self.convert_to_int(i[0]) for i in likeIts})
try:
button = a.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
except exceptions.NoSuchElementException:
continue
data.append({"likes":likes,"button":button,"article":a})
return data
def scroll(self,page_end=100):
find_elem = None
scroll_from = 0
scroll_limit = self.wd.execute_script("return document.body.scrollHeight")
i = 0
while not find_elem:
self.wd.execute_script("window.scrollTo(%d, %d);" % (scroll_from, scroll_from + scroll_limit))
scroll_from += scroll_limit
i += 1
if page_end and i >= page_end:
break
try:
find_elem = self.wd.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
find_elem.click()
except exceptions.ElementNotVisibleException:
find_elem = None
except exceptions.NoSuchElementException:
find_elem = None
def automate(self,unlike=False,page_end=100):
if self.status_report: print("Forcing Facebook to load the posts...")
self.scroll(page_end)
if self.status_report: print("Scrolled down %s times" % page_end)
if self.status_report: print("%s posts..." % ("Unliking" if unlike else "Liking"))
self.wd.execute_script("window.scrollTo(0,0);")
posts = self.get_posts()
num = 0
for p in posts:
if p["likes"]["Angry"] == 0 and p["likes"]["Sad"] == 0 and p["likes"]["Like"] >= 5:
article = p["article"]
self.wd.execute_script("arguments[0].scrollIntoView();", article)
button = article.find_element_by_css_selector("span#like-button.btn.btn-default.stat-item")
if true:
#button.get_attribute("aria-pressed") == ("true" if unlike else "false"):
num += 1
self.wd.execute_script("arguments[0].click();",button)
try:
p = article.find_element_by_tag_name("p").get_attribute("innerText")
p = p.replace("\n"," ").encode().decode("utf-8")
except exceptions.NoSuchElementException:
p = ""
except:
p = ""
if self.status_report: print(' - %s "%s"' % ("Unliked" if unlike else "Liked",p))
if self.status_report: print("%s %s posts" % ("Unliked" if unlike else "Liked",num))
def close(self):
self.wd.close()
username = "whatl0ol"
password = "tornike123"
pages = False
while pages is False:
inp = input("How many pages to go through? (default 100, 'all' for whole News Feed): ")
if inp.isdigit():
pages = int(inp)
elif inp == "all":
pages = None
unlike = None
while unlike is None:
inp = input("Do you want to Like (l) or Unlike (u) posts? ")
if inp == "l":
unlike = False
elif inp == "u":
unlike = True
bot = FacebookBot(username,password,status_report=True)
bot.automate(unlike=unlike, page_end=pages)
print("Finished")
print()
input("Return to exit")
try:
bot.close()
except:
pass

Related

How to search meal by name using Mealdb API for Python

In my objects.py I have this code for meals:
class Meal:
def __init__(self, meal_id, meal_name, meal_thumb):
self.__meal_id = meal_id
self.__meal_name = meal_name
self.__meal_thumb = meal_thumb
def get_meal_id(self):
return self.__meal_id
def set_meal_id(self, meal_id):
self.__meal_id = meal_id
def get_name(self):
return self.__meal_name
def set_name(self, meal_name):
self.__meal_name = meal_name
def get_meal_thumb(self):
return self.__meal_thumb
def set_meal_thumb(self, meal_thumb):
self.__meal_thumb = meal_thumb
In my requests.py I came up with:
def get_all_meals():
url = "https://www.themealdb.com/api/json/v1/1/search.php?f=a"
f = request.urlopen(url)
all_meals = []
try:
data = json.loads(f.read().decode('utf-8'))
for meal_data in data['meals']:
meal = Meal(meal_data['strMeal'],
meal_data['strMeal'],
meal_data['strMealThumb'])
all_meals.append(meal)
except(ValueError, KeyError, TypeError):
return None
return all_meals
def get_meal_by_name(meal):
url = "https://www.themealdb.com/api/json/v1/1/search.php?s=" + parse.quote(meal)
f = request.urlopen(url)
try:
data = json.loads(f.read().decode('utf-8'))
for meal_data in data['meals']:
meal = Meal(meal_data['idMeal'],
meal_data['strMeal'],
meal_data['strMealThumb'])
except(ValueError, KeyError, TypeError):
return None
return meal
I'm not sure if need get_all_meals() or just get_meal_by_name(meal).
In my recipes.py I have:
def list_meal_by_name():
lookup_meal = input("Enter Meal Name: ")
all_meals = requests.get_all_meals()
found = False
if all_meals is None:
print("Technical difficulties, please try again later.")
else:
for i in range(len(all_meals)):
meal = all_meals[i]
if meal.get_meal_id().lower() == lookup_meal.lower():
found = True
break
if found:
meal = lookup_meal
recipe = requests.get_meal_by_name(meal)
my_wrap = textwrap.TextWrapper(width=80)
wrap_list = my_wrap.wrap("Instructions: " + recipe.get_instructions())
for line in wrap_list:
print(line)
else:
print("Invalid meal name. Please try again.")
print()
I was trying to run the user input through the list of all meals in the Mealdb API. If that was found I wanted the meal and instructions to print, but it jumps to the else statement and prints "Invalid meal name. Please try again." I'm not sure what to code in the if statement to make it run and print properly. Also, the "recipe.get_instructions()" is a hint given for this project so I'm not sure what I need to do to make it work.

main function runs twice, but works normally second call in python

I'm writing a automation script which based on user input executes other scripts whose methods are called and fed the input as arguments.
Problem is, when the main script is first run, the user is asked for information twice.
After the second run, the script works as intended for the next runs without error.
import of function in main script
from spw import seaSec
#main function to call for pw resets
def menu ():
con = ""
while (con!= "no"):
empID = input("What is the employee ID ")
last4 = input("What are ")
answer = input("Which website would you like to go to ").lower()
if answer == "sea":
seaSec(empID, last4)
#Will add once OmniCo script works
#elif answer == "omni"
#omniCo(empID, last4)
con = input("Need help with anything else? (Enter y or n) ")
if con == "n":
quit()
menu()
def seaSec(empID, last4):
from **** import createTicket
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("http://wodapp/SecurityServices/Admin/FindUser.aspx")
driver.minimize_window()
#Input employee ID input to verify
ID = driver.find_element(By.ID, 'ContentPlaceHolder1_sapPersonnelNumberTextBox')
ID.send_keys(empID)
#submit information
Sub = driver.find_element(By.ID, "ContentPlaceHolder1_submitImageButton")
Sub.click()
#Hold SSN for verification, then compare to user input
VER = driver.find_element(By.ID, 'ContentPlaceHolder1_userRepeater_editImageButton_0')
VER.click()
num= driver.find_element(By.ID, "ContentPlaceHolder1_").get_attribute('value')
while cont != "0":
if (last4 == num):
cont = 0
break
elif (last4 != num):
print("Value does not match")
return False
firstName = driver.find_element(By.ID, "ContentPlaceHolder1_firstNameTextBox").get_attribute('value')
lastName = driver.find_element(By.ID, "ContentPlaceHolder1_lastNameTextBox").get_attribute('value')
fullName = firstName + " " + lastName
select = Select(driver.find_element(By.ID, "ContentPlaceHolder1_homeParkDropDownList"))
parkID = select.first_selected_option.text
driver.back()
choice = input("basic or xstore? ").lower()
def spw():
Reset = driver.find_element(By.ID, "ContentPlaceHolder1_userRepeater_resetPasswordImageButton_0")
Reset.click()
print(createTicket("pwd", parkID, empID, fullName, "Sea-Port" ))
driver.quit()
def xpw():
xStore = driver.find_element(By.ID, "ContentPlaceHolder1_userRepeater_manageXStoreImageButton_0")
xStore.click()
choice = input("Unlock or PW? ").lower()
if choice == "unlock":
unlock = driver.find_element(By.ID, "ContentPlaceHolder1_unlockImageButton")
unlock.click()
print(createTicket("unlock", parkID, empID, fullName, "Xstore"))
elif choice == "pw":
reset = driver.find_element(By.ID, "ContentPlaceHolder1_resetPasswordImageButton")
reset.click()
print(createTicket("pwd", parkID, empID, fullName, "Xstore"))
if choice == "basic":
spw()
elif choice == "xstore":
xpw()
driver.quit()

If there is no answer I want it to pass Python

If there is no answer I want it to pass. I don't want it to write in an excel table. If there is no answer, I want you to move on to the next question.
I'm sorry I don't know much English. If there is an answer, do not write anything in the excel table. skip to the next question
from encodings import utf_8
import people_also_ask as paa
from fake_useragent import UserAgent
ua = UserAgent()
while True:
input("Please make sure the queries are in \\query.txt file.\npress Enter to continue...")
try:
query_file = open("query.txt","r")
queries = query_file.readlines()
query_file.close()
break
except:
print("Error with the query.txt file...")
for query in queries:
res_file = open("result.csv","a",encoding="utf_8")
try:
query = query.replace("\n","")
except:
pass
print(f'Searching for "{query}"')
questions = paa.get_related_questions(query, 14)
questions.insert(0,query)
print("\n________________________\n")
main_q = True
for i in questions:
i = i.split('?')[0]
try:
answer = str(paa.get_answer(i)['response'])
if answer[-1].isdigit():
answer = answer[:-11]
print(f"Question:{i}?")
except Exception as e:
print(e)
print(f"Answer:{answer}")
if main_q:
a = ""
b = ""
main_q = False
else:
a = "<h2>"
b = "</h2>"
res_file.writelines(str(f'{a}{i}?{b},"<p>{answer}</p>",'))
print("______________________")
print("______________________")
res_file.writelines("\n")
res_file.close()
print("\nSearch Complete.")
input("Press any key to Exit!")
If you want to detect that the input is blank, then just add a condition in your code.
inputvar = input("Enter string: ")
if inputvar == "":
print("Blank input entered!")
else:
print(inputvar)
But just whatever you do, do not enter a .replace("", "None") code in your project because this can cause a serious error: Even if you enter an answer the input variable, it will enter None after each letter/symbol you enter!
Code:
from encodings import utf_8
import people_also_ask as paa
from fake_useragent import UserAgent
ua = UserAgent()
while True:
input("Please make sure the queries are in \\query.txt file.\npress Enter to continue...")
try:
query_file = open("query.txt", "r")
queries = query_file.readlines()
query_file.close()
break
except:
print("Error with the query.txt file...")
for query in queries:
res_file = open("result.csv", "a", encoding="utf_8")
try:
if query == "":
query = query.replace("\n", "")
else:
pass
except:
pass
print(f'Searching for "{query}"')
questions = paa.get_related_questions(query, 14)
questions.insert(0, query)
print("\n________________________\n")
main_q = True
for i in questions:
i = i.split('?')[0]
answer = str(paa.get_answer(i)['response'])
try:
if answer[-1].isdigit():
answer = answer[:-11]
print(f"Question:{i}?")
except Exception as e:
print(e)
print(f"Answer:{answer}")
if main_q:
a = ""
b = ""
main_q = False
else:
a = "<h2>"
b = "</h2>"
res_file.writelines(str(f'{a}{i}?{b},"<p>{answer}</p>",'))
print("______________________")
print("______________________")
res_file.writelines("\n")
res_file.close()
print("\nSearch Complete.")
input("Press any key to Exit!")

selenium click() method doesn't work after perfectly working a couple of hours before

I'm using selenium to like automatically some pictures. So the script searches for a word, clicks on the first picture, locates the like button then clicks on it.
The click button works to click on the picture but not to like it... I didn't change the identifier, so the class name is perfectly fine. I don't where the problem could come.
Here's my code :
'''
class Interact(Browser):
#click on the firt picture in the page
def firstpic_click(self):
time.sleep(2)
first = self.browser.find_element_by_class_name("kIKUG")
first.click()
#likes curent picture
def like_pic(self):
time.sleep(2)
like = self.browser.find_element_by_class_name("fr66n")
soup = bs(like.get_attribute('innerHTML'),'html.parser')
if (soup.find('svg')['aria-label'] == 'Like'):
like.click()
time.sleep(2)
#returns and clicks on next picture if any
def next_picture(self):
time.sleep(2)
try:
# nex = browser.find_element_by_xpath('//svg[#aria-label="Next"]')
next = self.browser.find_elements_by_class_name("wpO6b ")
soups = [bs(nextt.get_attribute('innerHTML'),'html.parser') for nextt in next]
for i in range(len(soups)):
#print(soups[i])
if (soups[i].find('svg')['aria-label'] == 'Next'):
next[i].click()
return next[i]
#nex = self.browser.find_element_by_xpath('//button[#class="wpO6b "]')
#time.sleep(1)
#return nex
except selenium.common.exceptions.NoSuchElementException:
return 0
#liking all the next pictures if any
def continue_liking(self):
while(True):
next_el = self.next_picture()
if next_el != False:
self.like_pic()
time.sleep(2)
next_el.click()
time.sleep(2)
else:
print("not found")
break
def word_search(self, search=1):
# word = input("what?")
word = "lol"
#search is the method of search
#looking for word in search box
if search == 0:
search_box = self.browser.find_element_by_xpath("//input[#aria-label='Search Input']")
search_box.send_keys("#"+word)
time.sleep(2)
#search_box.send_keys(Keys.RETURN)
#search_box.send_keys(Keys.RETURN)
search_box.submit()
time.sleep(5)
#type the website directly
if search == 1:
self.browser.get("https://www.instagram.com/explore/tags/" + word)
def liking_pictures(browser0):
browser0.implicitly_wait(5)
browser = Interact(browser0)
browser.word_search()
browser.firstpic_click()
browser.like_pic()
browser.next_picture()
browser.continue_liking()
time.sleep(10)
if __name__ == '__main__':
with browse() as browser0:
#unsubscribing(browser0)
liking_pictures(browser0)
'''
Thank you

python 2.7 - login try

Here are simple login scripts.
I have little bugs.
In a text file write:
name :test
password :123321
admin :0
I want to do:
if password and username exist then
#do code
else
#do code
import os
import sys
print "Hello to login - login(username,password)"
login = 0
att = 1
while login == 0:
#Check if user login/exist
Log = raw_input("Enter username: ")
if os.path.isfile(Log + ".txt"):
userfile = (Log+".txt")
f = open(userfile,"r")
Pass = raw_input("enter password: ")
Lines = f.readlines()
Password1 = Lines[1].split(":")
Passwordl = Lines[1].strip()
if Passwordl[10:] == Pass:
login = 1
break
elif att == 3:
print "you try to log in more then 3 time, user locked"
break
else:
print "username not exist or pass wrong"
att += 1
if login == 1:
print "Welcome "
You're problem is indenting- you want to indent everything from Log= to be within the while loop
import os
import sys
print "Hello to login - login(username,password)"
login = 0
att = 1
while login == 0:
#Check if user login/exist
Log = raw_input("Enter username: ")
if os.path.isfile(Log + ".txt"):
userfile = (Log+".txt")
f = open(userfile,"r")
Pass = raw_input("enter password: ")
Lines = f.readlines()
Password1 = Lines[1].split(":")
Passwordl = Lines[1].strip()
if Passwordl[10:] == Pass:
login = 1
break
elif att == 3:
print "you try to log in more then 3 time, user locked"
break
else:
print "username not exist or pass wrong"
att += 1

Categories

Resources