Description
stringlengths 9
105
| Link
stringlengths 45
135
| Code
stringlengths 10
26.8k
| Test_Case
stringlengths 9
202
| Merge
stringlengths 63
27k
|
---|---|---|---|---|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
# you can take any valid username
audience = ["sundarpichai", "virat.kholi", "rudymancuso"]
message = "testing of a bot"
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
# you can take any valid username
audience = ["sundarpichai", "virat.kholi", "rudymancuso"]
message = "testing of a bot"
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
class bot:
def __init__(self, username, password, audience, message):
# initializing the username
self.username = username
# initializing the password
self.password = password
# passing the list of user or initializing
self.user = user
# passing the message of user or initializing
self.message = message
# initializing the base url.
self.base_url = "https://www.instagram.com/"
# here it calls the driver to open chrome web browser.
self.bot = driver
# initializing the login function we will create
self.login()
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
class bot:
def __init__(self, username, password, audience, message):
# initializing the username
self.username = username
# initializing the password
self.password = password
# passing the list of user or initializing
self.user = user
# passing the message of user or initializing
self.message = message
# initializing the base url.
self.base_url = "https://www.instagram.com/"
# here it calls the driver to open chrome web browser.
self.bot = driver
# initializing the login function we will create
self.login()
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
def login(self):
self.bot.get(self.base_url)
# ENTERING THE USERNAME FOR LOGIN INTO INSTAGRAM
enter_username = WebDriverWait(self.bot, 20).until(
expected_conditions.presence_of_element_located((By.NAME, "username"))
)
enter_username.send_keys(self.username)
# ENTERING THE PASSWORD FOR LOGIN INTO INSTAGRAM
enter_password = WebDriverWait(self.bot, 20).until(
expected_conditions.presence_of_element_located((By.NAME, "password"))
)
enter_password.send_keys(self.password)
# RETURNING THE PASSWORD and login into the account
enter_password.send_keys(Keys.RETURN)
time.sleep(5)
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
def login(self):
self.bot.get(self.base_url)
# ENTERING THE USERNAME FOR LOGIN INTO INSTAGRAM
enter_username = WebDriverWait(self.bot, 20).until(
expected_conditions.presence_of_element_located((By.NAME, "username"))
)
enter_username.send_keys(self.username)
# ENTERING THE PASSWORD FOR LOGIN INTO INSTAGRAM
enter_password = WebDriverWait(self.bot, 20).until(
expected_conditions.presence_of_element_located((By.NAME, "password"))
)
enter_password.send_keys(self.password)
# RETURNING THE PASSWORD and login into the account
enter_password.send_keys(Keys.RETURN)
time.sleep(5)
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
# first pop-up box
self.bot.find_element_by_xpath(
'//*[@id="react-root"]/section/main/div/div/div/div/button'
).click()
time.sleep(3)
# 2nd pop-up box
self.bot.find_element_by_xpath("/html/body/div[4]/div/div/div/div[3]/button[2]").click()
time.sleep(4)
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
# first pop-up box
self.bot.find_element_by_xpath(
'//*[@id="react-root"]/section/main/div/div/div/div/button'
).click()
time.sleep(3)
# 2nd pop-up box
self.bot.find_element_by_xpath("/html/body/div[4]/div/div/div/div[3]/button[2]").click()
time.sleep(4)
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
# this will click on message(direct) option.
self.bot.find_element_by_xpath(
'//a[@class="xWeGp"]/*[name()="svg"][@aria-label="Direct"]'
).click()
time.sleep(3)
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
# this will click on message(direct) option.
self.bot.find_element_by_xpath(
'//a[@class="xWeGp"]/*[name()="svg"][@aria-label="Direct"]'
).click()
time.sleep(3)
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
# This will click on the pencil icon as shown in the figure.
self.bot.find_element_by_xpath(
'//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div/button'
).click()
time.sleep(2)
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
# This will click on the pencil icon as shown in the figure.
self.bot.find_element_by_xpath(
'//*[@id="react-root"]/section/div/div[2]/div/div/div[2]/div/button'
).click()
time.sleep(2)
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
for i in user:
# enter the username
self.bot.find_element_by_xpath(
"/html/body/div[4]/div/div/div[2]/div[1]/div/div[2]/input"
).send_keys(i)
time.sleep(2)
# click on the username
self.bot.find_element_by_xpath(
"/html/body/div[4]/div/div/div[2]/div[2]/div"
).click()
time.sleep(2)
# next button
self.bot.find_element_by_xpath(
"/html/body/div[4]/div/div/div[1]/div/div[2]/div/button"
).click()
time.sleep(2)
# click on message area
send = self.bot.find_element_by_xpath(
"/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea"
)
# types message
send.send_keys(self.message)
time.sleep(1)
# send message
send.send_keys(Keys.RETURN)
time.sleep(2)
# clicks on pencil icon
self.bot.find_element_by_xpath(
"/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[1]/div/div[3]/button"
).click()
time.sleep(2)
# here will take the next username from the user's list.
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
for i in user:
# enter the username
self.bot.find_element_by_xpath(
"/html/body/div[4]/div/div/div[2]/div[1]/div/div[2]/input"
).send_keys(i)
time.sleep(2)
# click on the username
self.bot.find_element_by_xpath(
"/html/body/div[4]/div/div/div[2]/div[2]/div"
).click()
time.sleep(2)
# next button
self.bot.find_element_by_xpath(
"/html/body/div[4]/div/div/div[1]/div/div[2]/div/button"
).click()
time.sleep(2)
# click on message area
send = self.bot.find_element_by_xpath(
"/html/body/div[1]/section/div/div[2]/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea"
)
# types message
send.send_keys(self.message)
time.sleep(1)
# send message
send.send_keys(Keys.RETURN)
time.sleep(2)
# clicks on pencil icon
self.bot.find_element_by_xpath(
"/html/body/div[1]/section/div/div[2]/div/div/div[1]/div[1]/div/div[3]/button"
).click()
time.sleep(2)
# here will take the next username from the user's list.
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
def init():
# you can even enter your personal account.
bot("username", "password", user, message_)
input("DONE")
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
def init():
# you can even enter your personal account.
bot("username", "password", user, message_)
input("DONE")
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
# calling this function will message everyone's
# that is on your user's list...:)
init()
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
# calling this function will message everyone's
# that is on your user's list...:)
init()
#Output : pip install selenium
[END]
|
Automate Instagram Messages using Python
|
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
|
# importing module
from selenium import webdriver
import os
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
# enter receiver user name
user = ["User_name", "User_name "]
message_ = "final test"
class bot:
def __init__(self, username, password, user, message):
self.username = username
self.password = password
self.user = user
self.message = message
self.base_url = "https://www.instagram.com/"
self.bot = driver
self.login()
def login(self):
self.bot.get(self.base_url)
enter_username = WebDriverWait(self.bot, 20).until(
expected_conditions.presence_of_element_located((By.NAME, "username"))
)
enter_username.send_keys(self.username)
enter_password = WebDriverWait(self.bot, 20).until(
expected_conditions.presence_of_element_located((By.NAME, "password"))
)
enter_password.send_keys(self.password)
enter_password.send_keys(Keys.RETURN)
time.sleep(5)
# first pop-up
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/div/div/div/button",
).click()
time.sleep(5)
# 2nd pop-up
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[3]/button[2]",
).click()
time.sleep(5)
# direct button
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[1]/div/div/div/div/div[2]/div[4]/div/a",
).click()
time.sleep(3)
# clicks on pencil icon
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[2]/div/section/div/div/div/div/div[1]/div[1]/div/div[3]/button",
).click()
time.sleep(2)
for i in user:
# enter the username
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div[2]/div[1]/div/div[2]/input",
).send_keys(i)
time.sleep(3)
# click on the username
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div[2]/div[2]/div[1]/div/div[3]/button",
).click()
time.sleep(4)
# next button
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[3]/div/button",
).click()
time.sleep(4)
# click on message area
send = self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[2]/div/section/div/div/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea",
)
# types message
send.send_keys(self.message)
time.sleep(1)
# send message
send.send_keys(Keys.RETURN)
time.sleep(2)
# clicks on direct option or pencil icon
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[2]/div/section/div/div/div/div/div[1]/div[1]/div/div[3]/button",
).click()
time.sleep(4)
def init():
bot("username", "password", user, message_)
# when our program ends it will show "done".
input("DONE")
# calling the function
init()
|
#Output : pip install selenium
|
Automate Instagram Messages using Python
# importing module
from selenium import webdriver
import os
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.common.keys import Keys
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
# enter receiver user name
user = ["User_name", "User_name "]
message_ = "final test"
class bot:
def __init__(self, username, password, user, message):
self.username = username
self.password = password
self.user = user
self.message = message
self.base_url = "https://www.instagram.com/"
self.bot = driver
self.login()
def login(self):
self.bot.get(self.base_url)
enter_username = WebDriverWait(self.bot, 20).until(
expected_conditions.presence_of_element_located((By.NAME, "username"))
)
enter_username.send_keys(self.username)
enter_password = WebDriverWait(self.bot, 20).until(
expected_conditions.presence_of_element_located((By.NAME, "password"))
)
enter_password.send_keys(self.password)
enter_password.send_keys(Keys.RETURN)
time.sleep(5)
# first pop-up
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[2]/section/main/div/div/div/div/button",
).click()
time.sleep(5)
# 2nd pop-up
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div/div[3]/button[2]",
).click()
time.sleep(5)
# direct button
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div[1]/div/div/div/div/div[2]/div[4]/div/a",
).click()
time.sleep(3)
# clicks on pencil icon
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[2]/div/section/div/div/div/div/div[1]/div[1]/div/div[3]/button",
).click()
time.sleep(2)
for i in user:
# enter the username
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div[2]/div[1]/div/div[2]/input",
).send_keys(i)
time.sleep(3)
# click on the username
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div[2]/div[2]/div[1]/div/div[3]/button",
).click()
time.sleep(4)
# next button
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div/div[2]/div/div/div/div/div[2]/div/div[1]/div/div[3]/div/button",
).click()
time.sleep(4)
# click on message area
send = self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[2]/div/section/div/div/div/div/div[2]/div[2]/div/div[2]/div/div/div[2]/textarea",
)
# types message
send.send_keys(self.message)
time.sleep(1)
# send message
send.send_keys(Keys.RETURN)
time.sleep(2)
# clicks on direct option or pencil icon
self.bot.find_element(
By.XPATH,
"/html/body/div[1]/div/div/div/div[1]/div/div/div/div[1]/div[1]/div/div[2]/div/section/div/div/div/div/div[1]/div[1]/div/div[3]/button",
).click()
time.sleep(4)
def init():
bot("username", "password", user, message_)
# when our program ends it will show "done".
input("DONE")
# calling the function
init()
#Output : pip install selenium
[END]
|
Automating Happy Birthday post on Facebook
|
https://www.geeksforgeeks.org/python-automating-happy-birthday-post-on-facebook-using-selenium/
|
# importing necessary classes
# from different modules
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
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
import time
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
browser = webdriver.Chrome("chromedriver.exe")
# open facebook.com using get() method
browser.get("https://www.facebook.com/")
# user_name or e-mail id
username = "[email protected]"
# getting password from text file
with open("test.txt", "r") as myfile:
password = myfile.read().replace("\n", "")
print("Let's Begin")
element = browser.find_elements_by_xpath('//*[@id ="email"]')
element[0].send_keys(username)
print("Username Entered")
element = browser.find_element_by_xpath('//*[@id ="pass"]')
element.send_keys(password)
print("Password Entered")
# logging in
log_in = browser.find_elements_by_id("loginbutton")
log_in[0].click()
print("Login Successful")
browser.get("https://www.facebook.com/events/birthdays/")
feed = "Happy Birthday !"
element = browser.find_elements_by_xpath(
"//*[@class ='enter_submit\
uiTextareaNoResize uiTextareaAutogrow uiStreamInlineTextarea\
inlineReplyTextArea mentionsTextarea textInput']"
)
cnt = 0
for el in element:
cnt += 1
element_id = str(el.get_attribute("id"))
XPATH = '//*[@id ="' + element_id + '"]'
post_field = browser.find_element_by_xpath(XPATH)
post_field.send_keys(feed)
post_field.send_keys(Keys.RETURN)
print("Birthday Wish posted for friend" + str(cnt))
# Close the browser
browser.close()
|
#Output : pip install selenium
|
Automating Happy Birthday post on Facebook
# importing necessary classes
# from different modules
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
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.keys import Keys
import time
chrome_options = webdriver.ChromeOptions()
prefs = {"profile.default_content_setting_values.notifications": 2}
chrome_options.add_experimental_option("prefs", prefs)
browser = webdriver.Chrome("chromedriver.exe")
# open facebook.com using get() method
browser.get("https://www.facebook.com/")
# user_name or e-mail id
username = "[email protected]"
# getting password from text file
with open("test.txt", "r") as myfile:
password = myfile.read().replace("\n", "")
print("Let's Begin")
element = browser.find_elements_by_xpath('//*[@id ="email"]')
element[0].send_keys(username)
print("Username Entered")
element = browser.find_element_by_xpath('//*[@id ="pass"]')
element.send_keys(password)
print("Password Entered")
# logging in
log_in = browser.find_elements_by_id("loginbutton")
log_in[0].click()
print("Login Successful")
browser.get("https://www.facebook.com/events/birthdays/")
feed = "Happy Birthday !"
element = browser.find_elements_by_xpath(
"//*[@class ='enter_submit\
uiTextareaNoResize uiTextareaAutogrow uiStreamInlineTextarea\
inlineReplyTextArea mentionsTextarea textInput']"
)
cnt = 0
for el in element:
cnt += 1
element_id = str(el.get_attribute("id"))
XPATH = '//*[@id ="' + element_id + '"]'
post_field = browser.find_element_by_xpath(XPATH)
post_field.send_keys(feed)
post_field.send_keys(Keys.RETURN)
print("Birthday Wish posted for friend" + str(cnt))
# Close the browser
browser.close()
#Output : pip install selenium
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
class Square:
def __init__(self, side):
"""creates a square having the given side"""
self.side = side
def area(self):
"""returns area of the square"""
return self.side**2
def perimeter(self):
"""returns perimeter of the square"""
return 4 * self.side
def __repr__(self):
"""declares how a Square object should be printed"""
s = (
"Square with side = "
+ str(self.side)
+ "\n"
+ "Area = "
+ str(self.area())
+ "\n"
+ "Perimeter = "
+ str(self.perimeter())
)
return s
if __name__ == "__main__":
# read input from the user
side = int(input("enter the side length to create a Square: "))
# create a square with the provided side
square = Square(side)
# print the created square
print(square)
|
#Output : ---Software_Testing
|
Automated software testing with Python
class Square:
def __init__(self, side):
"""creates a square having the given side"""
self.side = side
def area(self):
"""returns area of the square"""
return self.side**2
def perimeter(self):
"""returns perimeter of the square"""
return 4 * self.side
def __repr__(self):
"""declares how a Square object should be printed"""
s = (
"Square with side = "
+ str(self.side)
+ "\n"
+ "Area = "
+ str(self.area())
+ "\n"
+ "Perimeter = "
+ str(self.perimeter())
)
return s
if __name__ == "__main__":
# read input from the user
side = int(input("enter the side length to create a Square: "))
# create a square with the provided side
square = Square(side)
# print the created square
print(square)
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
def test_area(self):
# testing the method Square.area().
sq = Square(2) # creates a Square of side 2 units.
# test if the area of the above square is 4 units,
# display an error message if it's not.
self.assertEqual(
sq.area(), 4, f"Area is shown {sq.area()} for side = {sq.side} units"
)
|
#Output : ---Software_Testing
|
Automated software testing with Python
def test_area(self):
# testing the method Square.area().
sq = Square(2) # creates a Square of side 2 units.
# test if the area of the above square is 4 units,
# display an error message if it's not.
self.assertEqual(
sq.area(), 4, f"Area is shown {sq.area()} for side = {sq.side} units"
)
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
if __name__ == "__main__":
unittest.main()
|
#Output : ---Software_Testing
|
Automated software testing with Python
if __name__ == "__main__":
unittest.main()
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
import unittest
from .. import app
class TestSum(unittest.TestCase):
def test_area(self):
sq = app.Square(2)
self.assertEqual(sq.area(), 4, f"Area is shown {sq.area()} rather than 9")
if __name__ == "__main__":
unittest.main()
|
#Output : ---Software_Testing
|
Automated software testing with Python
import unittest
from .. import app
class TestSum(unittest.TestCase):
def test_area(self):
sq = app.Square(2)
self.assertEqual(sq.area(), 4, f"Area is shown {sq.area()} rather than 9")
if __name__ == "__main__":
unittest.main()
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
import unittest
from .. import app
class TestSum(unittest.TestCase):
def test_area(self):
sq = app.Square(2)
self.assertEqual(sq.area(), 4, f"Area is shown {sq.area()} rather than 9")
def test_area_negative(self):
sq = app.Square(-3)
self.assertEqual(sq.area(), -1, f"Area is shown {sq.area()} rather than -1")
def test_perimeter(self):
sq = app.Square(5)
self.assertEqual(
sq.perimeter(), 20, f"Perimeter is {sq.perimeter()} rather than 20"
)
def test_perimeter_negative(self):
sq = app.Square(-6)
self.assertEqual(
sq.perimeter(), -1, f"Perimeter is {sq.perimeter()} rather than -1"
)
if __name__ == "__main__":
unittest.main()
|
#Output : ---Software_Testing
|
Automated software testing with Python
import unittest
from .. import app
class TestSum(unittest.TestCase):
def test_area(self):
sq = app.Square(2)
self.assertEqual(sq.area(), 4, f"Area is shown {sq.area()} rather than 9")
def test_area_negative(self):
sq = app.Square(-3)
self.assertEqual(sq.area(), -1, f"Area is shown {sq.area()} rather than -1")
def test_perimeter(self):
sq = app.Square(5)
self.assertEqual(
sq.perimeter(), 20, f"Perimeter is {sq.perimeter()} rather than 20"
)
def test_perimeter_negative(self):
sq = app.Square(-6)
self.assertEqual(
sq.perimeter(), -1, f"Perimeter is {sq.perimeter()} rather than -1"
)
if __name__ == "__main__":
unittest.main()
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
from .. import app??????def test_file1_area():????????????????????????sq = app.Square(2)????????????????????????ass"area for side {sq.side} units is {sq.area()}"??def test_file1_perimeter():????????sq = app.Square(-1)????????assert sq.perimeter() == -1,????????????????f'perimeter is shown {sq.perimeter()} rather than -1'
|
#Output : ---Software_Testing
|
Automated software testing with Python
from .. import app??????def test_file1_area():????????????????????????sq = app.Square(2)????????????????????????ass"area for side {sq.side} units is {sq.area()}"??def test_file1_perimeter():????????sq = app.Square(-1)????????assert sq.perimeter() == -1,????????????????f'perimeter is shown {sq.perimeter()} rather than -1'
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
# @pytest.mark.<tag_name>@pytest.mark.area??????????????????????????????def test_file1_area():????????????????????????sq = app.Square(2)???????????"area for side {sq.side} units is {sq.area()}"
|
#Output : ---Software_Testing
|
Automated software testing with Python
# @pytest.mark.<tag_name>@pytest.mark.area??????????????????????????????def test_file1_area():????????????????????????sq = app.Square(2)???????????"area for side {sq.side} units is {sq.area()}"
#Output : ---Software_Testing
[END]
|
Automate Google Search
|
https://www.geeksforgeeks.org/python-automate-google-search-using-selenium/
|
from selenium import webdriver
# Taking input from user
search_string = input("Input the URL or string you want to search for:")
# This is done to structure the string
# into search url.(This can be ignored)
search_string = search_string.replace(" ", "+")
# Assigning the browser variable with chromedriver of Chrome.
# Any other browser and its respective webdriver
# like geckodriver for Mozilla Firefox can be used
browser = webdriver.Chrome("chromedriver")
for i in range(1):
matched_elements = browser.get(
"https://www.google.com/search?q=" + search_string + "&start=" + str(i)
)
|
#Output :
|
Automate Google Search
from selenium import webdriver
# Taking input from user
search_string = input("Input the URL or string you want to search for:")
# This is done to structure the string
# into search url.(This can be ignored)
search_string = search_string.replace(" ", "+")
# Assigning the browser variable with chromedriver of Chrome.
# Any other browser and its respective webdriver
# like geckodriver for Mozilla Firefox can be used
browser = webdriver.Chrome("chromedriver")
for i in range(1):
matched_elements = browser.get(
"https://www.google.com/search?q=" + search_string + "&start=" + str(i)
)
#Output :
[END]
|
Automate Google Search
|
https://www.geeksforgeeks.org/python-automate-google-search-using-selenium/
|
from selenium import webdriver
import sys
# function to convert a list into string
def convert(s):
str1 = ""
return str1.join(s)
# Assign the arguments passed to a variable search_string
search_string = sys.argv[1:]
# The argument passed to the program is accepted
# as list, it is needed to convert that into string
search_string = convert(search_string)
# This is done to structure the string
# into search url.(This can be ignored)
search_string = search_string.replace(" ", "+")
# Assigning the browser variable with chromedriver of Chrome.
# Any other browser and its respective webdriver
# like geckodriver for Mozilla Firefox can be used
browser = webdriver.Chrome("chromedriver")
for i in range(1):
matched_elements = browser.get(
"https://www.google.com/search?q=" + search_string + "&start=" + str(i)
)
|
#Output :
|
Automate Google Search
from selenium import webdriver
import sys
# function to convert a list into string
def convert(s):
str1 = ""
return str1.join(s)
# Assign the arguments passed to a variable search_string
search_string = sys.argv[1:]
# The argument passed to the program is accepted
# as list, it is needed to convert that into string
search_string = convert(search_string)
# This is done to structure the string
# into search url.(This can be ignored)
search_string = search_string.replace(" ", "+")
# Assigning the browser variable with chromedriver of Chrome.
# Any other browser and its respective webdriver
# like geckodriver for Mozilla Firefox can be used
browser = webdriver.Chrome("chromedriver")
for i in range(1):
matched_elements = browser.get(
"https://www.google.com/search?q=" + search_string + "&start=" + str(i)
)
#Output :
[END]
|
Automate linkedin connections using Python
|
https://www.geeksforgeeks.org/automate-linkedin-connections-using-python/
|
# connect python with webbrowser-chrome
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyautogui as pag
def login():
# Getting the login element
username = driver.find_element_by_id("login-email")
# Sending the keys for username
username.send_keys("username")
# Getting the password element
password = driver.find_element_by_id("login-password")
# Sending the keys for password
password.send_keys("password")
# Getting the tag for submit button
driver.find_element_by_id("login-submit").click()
def goto_network():
driver.find_element_by_id("mynetwork-tab-icon").click()
def send_requests():
# Number of requests you want to send
n = input("Number of requests: ")
for i in range(0, n):
# position(in px) of connection button
pag.click(880, 770)
print("Done !")
def main():
# url of LinkedIn
url = "http://linkedin.com/"
# url of LinkedIn network page
network_url = "http://linkedin.com / mynetwork/"
# path to browser web driver
driver = webdriver.Chrome("C:\\Program Files\\Web Driver\\chromedriver.exe")
driver.get(url)
# Driver's code
if __name__ == __main__:
main()
|
#Output : pip install selenium
|
Automate linkedin connections using Python
# connect python with webbrowser-chrome
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyautogui as pag
def login():
# Getting the login element
username = driver.find_element_by_id("login-email")
# Sending the keys for username
username.send_keys("username")
# Getting the password element
password = driver.find_element_by_id("login-password")
# Sending the keys for password
password.send_keys("password")
# Getting the tag for submit button
driver.find_element_by_id("login-submit").click()
def goto_network():
driver.find_element_by_id("mynetwork-tab-icon").click()
def send_requests():
# Number of requests you want to send
n = input("Number of requests: ")
for i in range(0, n):
# position(in px) of connection button
pag.click(880, 770)
print("Done !")
def main():
# url of LinkedIn
url = "http://linkedin.com/"
# url of LinkedIn network page
network_url = "http://linkedin.com / mynetwork/"
# path to browser web driver
driver = webdriver.Chrome("C:\\Program Files\\Web Driver\\chromedriver.exe")
driver.get(url)
# Driver's code
if __name__ == __main__:
main()
#Output : pip install selenium
[END]
|
Automated Trading using Python
|
https://www.geeksforgeeks.org/automated-trading-using-python/
|
import pandas as pd
import quandl as qd
qd.ApiConfig.api_key = "API KEY"
msft_data = qd.get("EOD/MSFT", start_date="2010-01-01", end_date="2020-01-01")
msft_data.head()
|
#Output : pip install quandl
|
Automated Trading using Python
import pandas as pd
import quandl as qd
qd.ApiConfig.api_key = "API KEY"
msft_data = qd.get("EOD/MSFT", start_date="2010-01-01", end_date="2020-01-01")
msft_data.head()
#Output : pip install quandl
[END]
|
Automated Trading using Python
|
https://www.geeksforgeeks.org/automated-trading-using-python/
|
# Import numpy package
import numpy as np
# assign `Adj Close` to `close_price`
close_price = msft_data[["Adj_Close"]]
# returns as fractional change
daily_return = close_price.pct_change()
# replacing NA values with 0
daily_return.fillna(0, inplace=True)
print(daily_return)
|
#Output : pip install quandl
|
Automated Trading using Python
# Import numpy package
import numpy as np
# assign `Adj Close` to `close_price`
close_price = msft_data[["Adj_Close"]]
# returns as fractional change
daily_return = close_price.pct_change()
# replacing NA values with 0
daily_return.fillna(0, inplace=True)
print(daily_return)
#Output : pip install quandl
[END]
|
Automated Trading using Python
|
https://www.geeksforgeeks.org/automated-trading-using-python/
|
# assigning adjusted closing prices
# to adj_prices
adj_price = msft_data["Adj_Close"]
# calculate the moving average
mav = adj_price.rolling(window=50).mean()
# print the result
print(mav[-10:])
|
#Output : pip install quandl
|
Automated Trading using Python
# assigning adjusted closing prices
# to adj_prices
adj_price = msft_data["Adj_Close"]
# calculate the moving average
mav = adj_price.rolling(window=50).mean()
# print the result
print(mav[-10:])
#Output : pip install quandl
[END]
|
Automated Trading using Python
|
https://www.geeksforgeeks.org/automated-trading-using-python/
|
# import the matplotlib package
# to see the plot
import matplotlib.pyplot as plt
adj_price.plot()
|
#Output : pip install quandl
|
Automated Trading using Python
# import the matplotlib package
# to see the plot
import matplotlib.pyplot as plt
adj_price.plot()
#Output : pip install quandl
[END]
|
Automated Trading using Python
|
https://www.geeksforgeeks.org/automated-trading-using-python/
|
mav.plot()
|
#Output : pip install quandl
|
Automated Trading using Python
mav.plot()
#Output : pip install quandl
[END]
|
Automated Trading using Python
|
https://www.geeksforgeeks.org/automated-trading-using-python/
|
# import the matplotlib package
# to see the plot
import matplotlib.pyplot as plt
adj_price.plot()
mav.plot()
|
#Output : pip install quandl
|
Automated Trading using Python
# import the matplotlib package
# to see the plot
import matplotlib.pyplot as plt
adj_price.plot()
mav.plot()
#Output : pip install quandl
[END]
|
Bulk Posting on Facebook Pages using Selementsenium
|
https://www.geeksforgeeks.org/bulk-posting-on-facebook-pages-using-selenium/
|
# Social Bot Version 1 Codes:??????from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport timeimport jsonimport os????????????class Social_bot:????????????????????????def __init__(self):??????????????????????????????????????????????????????# instance/class variables?????"https://www.facebook.com/"??????????????????# Facebook Page Menu Url????????????????self.page_ref = "https://www.facebook.com/pages/?category=your_pages&ref=bookmarks"??????????????????# Chrome Driver path, Important????????????????self.chromium_path = os.path.abspath("chromedriver.exe")??????????????????????????????????????????????????????# By default session is None,????????????????????????????????????????????????# will set after Starting the chrome????????????????????????????????????????????????self.browser_session = None??????????????????????????????????????????????????????# By default is set to 0,????????????????????????????????????????????????# if any website visits then????????????????????????????????????????????????# will be increment by one, only set to integer????????????????????????????????????????????????self.browser_visit = 0??????????????????????????????????????????????????????# By default is set to 0,?????????????????????????????????"//input[@id='email']"??????????????????# Xpath for Facebook login password????????????????self.pass_xpath = "//input[@id='pass']"??????????????????# For facebook login id credentials????????????????self.user = None??????????????????# For Facebook login password credentials????????????????self.password = None??????????????????# Xpath for facebook logout????????????????self.logout_fb = ["/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[4]/div[1]/span[1]/div[1]/div[1]/i[1]",????????????????????????????????????????????????????"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[4]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[5]/div[1]/div[1]/div[2]/div[1]",????????????????????????????????????????????????????"//div[@class='oajrlxb2 s1i5eluu gcieejh5 bn081pho humdl8nn izx4hr6d rq0escxv nhd2j8a9 j83agx80 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys d1544ag0 qt6c0cv9 tw6a2znq i1ao9s8h esuyzwwr f1sip0of lzcic4wl l9j0dhe7 abiwlrkh p8dawk7l beltcj47 p86d2i9g aot14ch1 kzx2olss cbu4d94t taijpn5t ni8dbmo4 stjgntxs k4urcfbm tv7at329']//div[@class='rq0escxv l9j0dhe7 du4w35lb j83agx80 pfnyh3mw taijpn5t bp9cbjyn owycx6da btwxx1t3 c4xchbtz by2jbhx6']"]??????????????????????????????????????????????????????# Page Name list????????????????????????????????????????????????self.fb_page_partial = None?????????????"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[4]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]",??????????????????????????????????????????????????????"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]",??????????????????????????????????????????????????????"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[2]/div[3]/div[4]/div[1]"]??????????????????????????????????????????????????????# Text posting content variable????????????????????????????????????????????????# Will be set via text_posting_content_load function????????????????????????????????????????????????# By default set to None????????????????????????????????????????????????self.textContents = None??????????????????????????????def initiate_chrome(self):????????????????????????????????????????????????# This function is to start chrome????????????????????????????????????????????????# Successful login will return 1??????????????????????????????????????????????????????if self.browser_session == None:????????????????????????????????????????????????????????????????????????self.browser_session = webdriver.Chrome(self.chromium_path)????????????????????????????????????????????????????????????????????????return 1????????????????????????????????????????????????else:????????????????????????????????????????????????????????????????????????return -1??????????????????????????????def close_sessi????????????# This function is to load page,????????????????# successful operation will return None??????????????????if path == None:??????????????????????????# if no url given, then it will return -1????????????????????????if self.browser_session == None:????????????????????????????????return -1????????????????????????else:????????????????????????????????self.browser_session.get(self.login_page)????????????????????????????????self.browser_visit += 1????????????????else:??????????????????????????# if session is not created, then will return -1????????????????????????if self.browser_session == None:????????????????????????????????return -1????????????????????????else:??????????????????????????????????# Successful operation will also????????????????????????????????# add one in instance variable to????????????????????????????????# track number of visited pages????????????????????????????????self.browser_session.get(path)????????????????????????????????self.browser_visit += 1??????????def reverse_visit(self, back_v=None):??????????????????????????????????????????????????????# This function is to go back to previous page????????????????????????????????????????????????# This function takes argument back_v for????????????????????????????????????????????????# telling function to back number of pages????????????????????????????????????????????????# If no value pass for back_v then it will go back to main page(starting page).??????????????????????????????????????????????????????if self.browser_visit == None:??????????????????????????????????????????????????????????????????????????????# if self.browser_visit instance????????????????????????????????????????????????????????????????????????# variable is None, then it will return -1????????????????????????????????????????????????????????????????????????return -1????????????????????????????????????????????????else:??????????????????????????????????????????????????????????????????????????????# if back_v is not given,???????????????????????????????????????????????????????????????kis given, then go back with the help of loop????????????????????????????????????????????????????????????????????????????????????????????????for vp in range(back_v):????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????self.browser_session.back()????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????self.browser_visit - = vp????????????????????????????????????????????????????????????????????????????????????????????????return 1??????????????????????????????def do_login(self, user_name=None, user_pass=None):??????????????????????????????????????????????????????# This function is to do login on social media,????????????????????????????????????????????????# takes two arguments user name and password????????????????????????????????????????????????# By default these argument set to None, and in no use??????????????????????????????????????????????????????if self.browser_session == None or.browser_visit will increment by 1????????????????????????????????????????????????????????????????????????# self.login will be set to 1 for successful login??????????????????????????????????????????????????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????????????????????????????????????????????????????????????self.user_xpath).send_keys(self.user)????????????????????????????????????????????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????????????????????????????????????????????????????????????self.pass_xpath).send_keys(self.password, Keys.ENTER)????????????????????????????????????????????????????????????????????????self.browser_visit += 1????????????????????????????????????????????????????????????????????????self.login = 1????????????????????????????????????????????????????????????????????????return 1??????????????????????????????def do_logout(self):?????????????????????????????????????????????????????????????# script for sometime.????????????????????????# Important bcz sometimes some xpath are not loaded,????????????????????????# and take time to load, so this function is important????????????????????????# Failed operation will return -1, and successful will return 1????????????????????????try:??????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????self.logout_fb[0]).click()??????????????????????????????????self.time_patterns()??????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????self.logout_fb[1]).click()??????????????????????????????????self.time_patterns()??????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????self.logout_fb[2]).click()????????????????????????????????return 1????????????????????????except:????????????????????????????????return -1??????????def time_patterns(self, tp=None):??????????????????# This function is to pause the script for sometime????????????????????????????????????????????????# Also takes argument as second,????????????????????????????????????????????????# if not given then it will????????????????????????????????????????????????# take by default seconds to wait????????????????????????????????????????????????# Successful operation will return 1??????????????????????????????????????????????????????if tp == None:????????????????????????????????????????????????????????????????????????time.sleep(self.time_pattern)????????????????????????????????????????????????????????????????????????return 1????????????????????????????????????????????????else:????????????????????????????????????????????????????????????????????????self.time_pattern = tp????????????????????????????????????????????????????????????????????????time.sleep(self.time_pattern)????????????????????????????????????????????????????????????????????????return 1??????????????????????????????def page_navigation_partial(self, pg_name):???#successful operation will also????????????????????????????????????????????????????????????????????????# increment the browser_visit by one??????????????????????????????????????????????????????????????????????????????self.browser_session.????????????????????????????????????????????????????????????????????????find_element_by_partial_link_text(pg_name).click()??????????????????????????????????????????????????????????????????????????????self.browser_visit += 1??????????????????????????????def page_posting(self):??????????????????????????????????????????????????????# This function is to do posting on website????????????????????????????????????????????????# Takes argument for posting text????????????????????????????????????????????????# Successful operation will return 1??????????????????????????????????????????????????????if self.browser_session == None:??????????????????????????????????????????????????????????????????????????????# if no browser_session?????????????????????????????????????????????????????????????#????????????????????????self.time_patterns()????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????self.fb_posting[1]).send_keys(????????????????????????????????Keys.ENTER, self.textContents)??????????????????????????self.time_patterns()??????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????self.fb_posting[2]).click()??????????????????????????self.time_patterns()????????????????????????self.reverse_visit(1)????????????????????????self.time_patterns()????????????????????????return 1??????????def credential_loads_using_json(self):??????????????????# This function is to load????????????????# credentials from json file????????????????# Will help to set credentials????????????????# instead of manual????????????????try:????????????????????????with open("credentials_load.json") as filePointer:????????????????????????????????????????????????????????????????????????????????????????????????contents = filePointer.read()???????????????????????????????????????????????????"Page Names"]?????????????????????????????????????????????"Email Address"]?????????????????????????????????????????????????"Password"]??????????????????????????????????????????????????????????????????????????????# for freeing the json memory part????????????????????????????????????????????????????????????????????????del(contents)????????????????????????????????????????????????????????????????????????return 1????????"PostingContents.txt", "r") as filePointer:????????????????????????????????????????????????????????????????????????????????????????????????textContents = filePointer.read()??????????????????????????????????????????????????????????????????????????????self.textContents = textContents????????????????????????????????????????????????????????????????????????return 1????????????????????????????????????????????????except:????????????????????????????????????????????????????????????????????????return -1????????????def soc_bot():??????????????????????????????# Creating an Instance of Social bot object????????????????????????bot = Social_bot()??????????????????????????????# Calling the initiate????????????????????????# chrome method to start the chrome????????????????????????bot.initiate_chrome()?????????"[+] Perform these tasks:\n1.Accept the 2FA if required to do \n2. Once FB Page Load, Please Block the Show Notification Dialog box. Once done, Please press to start the posting Script(Y/N) > ")??????????????????????????????# Below statement will pause the script????????????????????????# until you clear the above given instructions?????"Y":??????????????????????????????????????????????????????# will load the specified page????????????????????????????????????????????????bot.page_load(bot.page_ref)??????????????????????????????????????????????????????# for pausing the script for sometime????????????????????????????????????????????????bot.time_patterns()??????????????????????????????????????????????????????# Iterate through Page Names????????????????????????????????????????????????for link in bot.fb_page_partial:??????????????????????????????????????????????????????????????????????????????# load given facebook page by their name????????????????????????????????????????????????????????????????????????bot.page_navigat"[+] Posting Done on {}".format(link))??????????????????????????????????????????????????????# for logging out the facebook????????????????????????????????????????????????bot.do_logout()?????????????????????????????????????"[+] Posting Work Done!")??????????????????????????????????????????????????????# return 1 for successful operation????????????????????????????????????????????????return 1????????????????????????"__main__":??????????????"SOCIAL BOT SCRIPT INITIATED")?????????????????
|
#Output : pip install selenium
|
Bulk Posting on Facebook Pages using Selementsenium
# Social Bot Version 1 Codes:??????from selenium import webdriverfrom selenium.webdriver.common.keys import Keysimport timeimport jsonimport os????????????class Social_bot:????????????????????????def __init__(self):??????????????????????????????????????????????????????# instance/class variables?????"https://www.facebook.com/"??????????????????# Facebook Page Menu Url????????????????self.page_ref = "https://www.facebook.com/pages/?category=your_pages&ref=bookmarks"??????????????????# Chrome Driver path, Important????????????????self.chromium_path = os.path.abspath("chromedriver.exe")??????????????????????????????????????????????????????# By default session is None,????????????????????????????????????????????????# will set after Starting the chrome????????????????????????????????????????????????self.browser_session = None??????????????????????????????????????????????????????# By default is set to 0,????????????????????????????????????????????????# if any website visits then????????????????????????????????????????????????# will be increment by one, only set to integer????????????????????????????????????????????????self.browser_visit = 0??????????????????????????????????????????????????????# By default is set to 0,?????????????????????????????????"//input[@id='email']"??????????????????# Xpath for Facebook login password????????????????self.pass_xpath = "//input[@id='pass']"??????????????????# For facebook login id credentials????????????????self.user = None??????????????????# For Facebook login password credentials????????????????self.password = None??????????????????# Xpath for facebook logout????????????????self.logout_fb = ["/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[4]/div[1]/span[1]/div[1]/div[1]/i[1]",????????????????????????????????????????????????????"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[4]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[5]/div[1]/div[1]/div[2]/div[1]",????????????????????????????????????????????????????"//div[@class='oajrlxb2 s1i5eluu gcieejh5 bn081pho humdl8nn izx4hr6d rq0escxv nhd2j8a9 j83agx80 p7hjln8o kvgmc6g5 cxmmr5t8 oygrvhab hcukyx3x jb3vyjys d1544ag0 qt6c0cv9 tw6a2znq i1ao9s8h esuyzwwr f1sip0of lzcic4wl l9j0dhe7 abiwlrkh p8dawk7l beltcj47 p86d2i9g aot14ch1 kzx2olss cbu4d94t taijpn5t ni8dbmo4 stjgntxs k4urcfbm tv7at329']//div[@class='rq0escxv l9j0dhe7 du4w35lb j83agx80 pfnyh3mw taijpn5t bp9cbjyn owycx6da btwxx1t3 c4xchbtz by2jbhx6']"]??????????????????????????????????????????????????????# Page Name list????????????????????????????????????????????????self.fb_page_partial = None?????????????"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[3]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[4]/div[2]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]",??????????????????????????????????????????????????????"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[2]/div[2]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/div[1]",??????????????????????????????????????????????????????"/html[1]/body[1]/div[1]/div[1]/div[1]/div[1]/div[4]/div[1]/div[1]/div[1]/div[1]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[2]/div[3]/div[4]/div[1]"]??????????????????????????????????????????????????????# Text posting content variable????????????????????????????????????????????????# Will be set via text_posting_content_load function????????????????????????????????????????????????# By default set to None????????????????????????????????????????????????self.textContents = None??????????????????????????????def initiate_chrome(self):????????????????????????????????????????????????# This function is to start chrome????????????????????????????????????????????????# Successful login will return 1??????????????????????????????????????????????????????if self.browser_session == None:????????????????????????????????????????????????????????????????????????self.browser_session = webdriver.Chrome(self.chromium_path)????????????????????????????????????????????????????????????????????????return 1????????????????????????????????????????????????else:????????????????????????????????????????????????????????????????????????return -1??????????????????????????????def close_sessi????????????# This function is to load page,????????????????# successful operation will return None??????????????????if path == None:??????????????????????????# if no url given, then it will return -1????????????????????????if self.browser_session == None:????????????????????????????????return -1????????????????????????else:????????????????????????????????self.browser_session.get(self.login_page)????????????????????????????????self.browser_visit += 1????????????????else:??????????????????????????# if session is not created, then will return -1????????????????????????if self.browser_session == None:????????????????????????????????return -1????????????????????????else:??????????????????????????????????# Successful operation will also????????????????????????????????# add one in instance variable to????????????????????????????????# track number of visited pages????????????????????????????????self.browser_session.get(path)????????????????????????????????self.browser_visit += 1??????????def reverse_visit(self, back_v=None):??????????????????????????????????????????????????????# This function is to go back to previous page????????????????????????????????????????????????# This function takes argument back_v for????????????????????????????????????????????????# telling function to back number of pages????????????????????????????????????????????????# If no value pass for back_v then it will go back to main page(starting page).??????????????????????????????????????????????????????if self.browser_visit == None:??????????????????????????????????????????????????????????????????????????????# if self.browser_visit instance????????????????????????????????????????????????????????????????????????# variable is None, then it will return -1????????????????????????????????????????????????????????????????????????return -1????????????????????????????????????????????????else:??????????????????????????????????????????????????????????????????????????????# if back_v is not given,???????????????????????????????????????????????????????????????kis given, then go back with the help of loop????????????????????????????????????????????????????????????????????????????????????????????????for vp in range(back_v):????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????self.browser_session.back()????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????self.browser_visit - = vp????????????????????????????????????????????????????????????????????????????????????????????????return 1??????????????????????????????def do_login(self, user_name=None, user_pass=None):??????????????????????????????????????????????????????# This function is to do login on social media,????????????????????????????????????????????????# takes two arguments user name and password????????????????????????????????????????????????# By default these argument set to None, and in no use??????????????????????????????????????????????????????if self.browser_session == None or.browser_visit will increment by 1????????????????????????????????????????????????????????????????????????# self.login will be set to 1 for successful login??????????????????????????????????????????????????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????????????????????????????????????????????????????????????self.user_xpath).send_keys(self.user)????????????????????????????????????????????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????????????????????????????????????????????????????????????self.pass_xpath).send_keys(self.password, Keys.ENTER)????????????????????????????????????????????????????????????????????????self.browser_visit += 1????????????????????????????????????????????????????????????????????????self.login = 1????????????????????????????????????????????????????????????????????????return 1??????????????????????????????def do_logout(self):?????????????????????????????????????????????????????????????# script for sometime.????????????????????????# Important bcz sometimes some xpath are not loaded,????????????????????????# and take time to load, so this function is important????????????????????????# Failed operation will return -1, and successful will return 1????????????????????????try:??????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????self.logout_fb[0]).click()??????????????????????????????????self.time_patterns()??????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????self.logout_fb[1]).click()??????????????????????????????????self.time_patterns()??????????????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????????????self.logout_fb[2]).click()????????????????????????????????return 1????????????????????????except:????????????????????????????????return -1??????????def time_patterns(self, tp=None):??????????????????# This function is to pause the script for sometime????????????????????????????????????????????????# Also takes argument as second,????????????????????????????????????????????????# if not given then it will????????????????????????????????????????????????# take by default seconds to wait????????????????????????????????????????????????# Successful operation will return 1??????????????????????????????????????????????????????if tp == None:????????????????????????????????????????????????????????????????????????time.sleep(self.time_pattern)????????????????????????????????????????????????????????????????????????return 1????????????????????????????????????????????????else:????????????????????????????????????????????????????????????????????????self.time_pattern = tp????????????????????????????????????????????????????????????????????????time.sleep(self.time_pattern)????????????????????????????????????????????????????????????????????????return 1??????????????????????????????def page_navigation_partial(self, pg_name):???#successful operation will also????????????????????????????????????????????????????????????????????????# increment the browser_visit by one??????????????????????????????????????????????????????????????????????????????self.browser_session.????????????????????????????????????????????????????????????????????????find_element_by_partial_link_text(pg_name).click()??????????????????????????????????????????????????????????????????????????????self.browser_visit += 1??????????????????????????????def page_posting(self):??????????????????????????????????????????????????????# This function is to do posting on website????????????????????????????????????????????????# Takes argument for posting text????????????????????????????????????????????????# Successful operation will return 1??????????????????????????????????????????????????????if self.browser_session == None:??????????????????????????????????????????????????????????????????????????????# if no browser_session?????????????????????????????????????????????????????????????#????????????????????????self.time_patterns()????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????self.fb_posting[1]).send_keys(????????????????????????????????Keys.ENTER, self.textContents)??????????????????????????self.time_patterns()??????????????????????????self.browser_session.find_element_by_xpath(????????????????????????????????self.fb_posting[2]).click()??????????????????????????self.time_patterns()????????????????????????self.reverse_visit(1)????????????????????????self.time_patterns()????????????????????????return 1??????????def credential_loads_using_json(self):??????????????????# This function is to load????????????????# credentials from json file????????????????# Will help to set credentials????????????????# instead of manual????????????????try:????????????????????????with open("credentials_load.json") as filePointer:????????????????????????????????????????????????????????????????????????????????????????????????contents = filePointer.read()???????????????????????????????????????????????????"Page Names"]?????????????????????????????????????????????"Email Address"]?????????????????????????????????????????????????"Password"]??????????????????????????????????????????????????????????????????????????????# for freeing the json memory part????????????????????????????????????????????????????????????????????????del(contents)????????????????????????????????????????????????????????????????????????return 1????????"PostingContents.txt", "r") as filePointer:????????????????????????????????????????????????????????????????????????????????????????????????textContents = filePointer.read()??????????????????????????????????????????????????????????????????????????????self.textContents = textContents????????????????????????????????????????????????????????????????????????return 1????????????????????????????????????????????????except:????????????????????????????????????????????????????????????????????????return -1????????????def soc_bot():??????????????????????????????# Creating an Instance of Social bot object????????????????????????bot = Social_bot()??????????????????????????????# Calling the initiate????????????????????????# chrome method to start the chrome????????????????????????bot.initiate_chrome()?????????"[+] Perform these tasks:\n1.Accept the 2FA if required to do \n2. Once FB Page Load, Please Block the Show Notification Dialog box. Once done, Please press to start the posting Script(Y/N) > ")??????????????????????????????# Below statement will pause the script????????????????????????# until you clear the above given instructions?????"Y":??????????????????????????????????????????????????????# will load the specified page????????????????????????????????????????????????bot.page_load(bot.page_ref)??????????????????????????????????????????????????????# for pausing the script for sometime????????????????????????????????????????????????bot.time_patterns()??????????????????????????????????????????????????????# Iterate through Page Names????????????????????????????????????????????????for link in bot.fb_page_partial:??????????????????????????????????????????????????????????????????????????????# load given facebook page by their name????????????????????????????????????????????????????????????????????????bot.page_navigat"[+] Posting Done on {}".format(link))??????????????????????????????????????????????????????# for logging out the facebook????????????????????????????????????????????????bot.do_logout()?????????????????????????????????????"[+] Posting Work Done!")??????????????????????????????????????????????????????# return 1 for successful operation????????????????????????????????????????????????return 1????????????????????????"__main__":??????????????"SOCIAL BOT SCRIPT INITIATED")?????????????????
#Output : pip install selenium
[END]
|
Share WhatsApp Web without Scanning QR code using Python
|
https://www.geeksforgeeks.org/share-whatsapp-web-without-scanning-qr-code-using-python/
|
function getResultFromRequest(request) {????????????????????????return new Promise((resolve, reject) => {????????????????????????????????????????????????request.onsuccess = function (event) {????????????????????????????????????????????????????????????????????????resolve(request.result);??????"wawc");????????????????????????return await getResultFromRequest(request);}????????????async function readAllKeyValuePairs() {????????????????????????var db = await getDB();?"user").objectStore("user");????????????????????????var request = objectStore.getAll();??????????????????????????????????????????return await getResultFromRequest(request);}????????????session
|
#Output : python session_generator.py session.wa
|
Share WhatsApp Web without Scanning QR code using Python
function getResultFromRequest(request) {????????????????????????return new Promise((resolve, reject) => {????????????????????????????????????????????????request.onsuccess = function (event) {????????????????????????????????????????????????????????????????????????resolve(request.result);??????"wawc");????????????????????????return await getResultFromRequest(request);}????????????async function readAllKeyValuePairs() {????????????????????????var db = await getDB();?"user").objectStore("user");????????????????????????var request = objectStore.getAll();??????????????????????????????????????????return await getResultFromRequest(request);}????????????session
#Output : python session_generator.py session.wa
[END]
|
Share WhatsApp Web without Scanning QR code using Python
|
https://www.geeksforgeeks.org/share-whatsapp-web-without-scanning-qr-code-using-python/
|
JSON.stringify(session)
|
#Output : python session_generator.py session.wa
|
Share WhatsApp Web without Scanning QR code using Python
JSON.stringify(session)
#Output : python session_generator.py session.wa
[END]
|
Share WhatsApp Web without Scanning QR code using Python
|
https://www.geeksforgeeks.org/share-whatsapp-web-without-scanning-qr-code-using-python/
|
function getResultFromRequest(request) {????????????????????????return new Promise((resolve, reject) => {????????????????????????????????????????????????request.onsuccess = function(event) {????????????????????????????????????????????????????????????????????????resolve(request.result);?????"wawc");????????????????????????return await getResultFromRequest(request);}????????????async function injectSession(SESSION_STRING) {????????????????????????var session = JSON.parse(SESSION_STRING);????????????????????????var db ="user", "readwrite").objectStore("user");????????????????????????for(var keyValue of session) {????????????????????????????????????????????????var request = objectStore.put(keyValue);???????????????????????????????????????"";await injectSession(SESSION_STRING);
|
#Output : python session_generator.py session.wa
|
Share WhatsApp Web without Scanning QR code using Python
function getResultFromRequest(request) {????????????????????????return new Promise((resolve, reject) => {????????????????????????????????????????????????request.onsuccess = function(event) {????????????????????????????????????????????????????????????????????????resolve(request.result);?????"wawc");????????????????????????return await getResultFromRequest(request);}????????????async function injectSession(SESSION_STRING) {????????????????????????var session = JSON.parse(SESSION_STRING);????????????????????????var db ="user", "readwrite").objectStore("user");????????????????????????for(var keyValue of session) {????????????????????????????????????????????????var request = objectStore.put(keyValue);???????????????????????????????????????"";await injectSession(SESSION_STRING);
#Output : python session_generator.py session.wa
[END]
|
Share WhatsApp Web without Scanning QR code using Python
|
https://www.geeksforgeeks.org/share-whatsapp-web-without-scanning-qr-code-using-python/
|
def _wait_for_presence_of_an_element(browser, selector):
element = None
try:
element = WebDriverWait(browser, DEFAULT_WAIT).until(
EC.presence_of_element_located(selector)
)
except:
pass
finally:
return element
|
#Output : python session_generator.py session.wa
|
Share WhatsApp Web without Scanning QR code using Python
def _wait_for_presence_of_an_element(browser, selector):
element = None
try:
element = WebDriverWait(browser, DEFAULT_WAIT).until(
EC.presence_of_element_located(selector)
)
except:
pass
finally:
return element
#Output : python session_generator.py session.wa
[END]
|
Share WhatsApp Web without Scanning QR code using Python
|
https://www.geeksforgeeks.org/share-whatsapp-web-without-scanning-qr-code-using-python/
|
def sessionGenerator(sessionFilePath):
# 1.1 Open Chrome browser
browser = webdriver.Chrome()
# 1.2 Open Web Whatsapp
browser.get("https://web.whatsapp.com/")
# 1.3 Ask user to scan QR code
print("Waiting for QR code scan...")
# 1.4 Wait for QR code to be scanned
_wait_for_presence_of_an_element(browser, MAIN_SEARCH_BAR__SEARCH_ICON)
# 1.5 Execute javascript in browser and
# extract the session text
session = browser.execute_script(EXTRACT_SESSION)
# 1.6 Save file with session text file with
# custom file extension ".wa"
with open(sessionFilePath, "w", encoding="utf-8") as sessionFile:
sessionFile.write(str(session))
print("Your session file is saved to: " + sessionFilePath)
# 1.7 Close the browser
browser.close()
|
#Output : python session_generator.py session.wa
|
Share WhatsApp Web without Scanning QR code using Python
def sessionGenerator(sessionFilePath):
# 1.1 Open Chrome browser
browser = webdriver.Chrome()
# 1.2 Open Web Whatsapp
browser.get("https://web.whatsapp.com/")
# 1.3 Ask user to scan QR code
print("Waiting for QR code scan...")
# 1.4 Wait for QR code to be scanned
_wait_for_presence_of_an_element(browser, MAIN_SEARCH_BAR__SEARCH_ICON)
# 1.5 Execute javascript in browser and
# extract the session text
session = browser.execute_script(EXTRACT_SESSION)
# 1.6 Save file with session text file with
# custom file extension ".wa"
with open(sessionFilePath, "w", encoding="utf-8") as sessionFile:
sessionFile.write(str(session))
print("Your session file is saved to: " + sessionFilePath)
# 1.7 Close the browser
browser.close()
#Output : python session_generator.py session.wa
[END]
|
Share WhatsApp Web without Scanning QR code using Python
|
https://www.geeksforgeeks.org/share-whatsapp-web-without-scanning-qr-code-using-python/
|
from session import *
import sys
# Take session file path as command line
# argument and passed to following method
sessionFilePath = sys.argv[1]
sessionGenerator(sessionFilePath)
|
#Output : python session_generator.py session.wa
|
Share WhatsApp Web without Scanning QR code using Python
from session import *
import sys
# Take session file path as command line
# argument and passed to following method
sessionFilePath = sys.argv[1]
sessionGenerator(sessionFilePath)
#Output : python session_generator.py session.wa
[END]
|
Share WhatsApp Web without Scanning QR code using Python
|
https://www.geeksforgeeks.org/share-whatsapp-web-without-scanning-qr-code-using-python/
|
def sessionOpener(sessionFilePath):
# 2.1 Verify that session file is exist
if sessionFilePath == "":
raise IOError('"' + sessionFilePath + '" is not exist.')
# 2.2 Read the given file into "session" variable
with open(sessionFilePath, "r", encoding="utf-8") as sessionFile:
session = sessionFile.read()
# 2.3 Open Chrome browser
browser = webdriver.Chrome()
# 2.4 Open Web Whatsapp
browser.get("https://web.whatsapp.com/")
# 2.5 Wait for Web Whatsapp to be loaded properly
_wait_for_presence_of_an_element(browser, QR_CODE)
# 2.6 Execute javascript in browser to inject
# session by using variable "session"
print("Injecting session...")
browser.execute_script(INJECT_SESSION, session)
# 2.7 Refresh the page
browser.refresh()
# 2.8 Ask for user to enter any key to close browser
input("Press enter to close browser.")
|
#Output : python session_generator.py session.wa
|
Share WhatsApp Web without Scanning QR code using Python
def sessionOpener(sessionFilePath):
# 2.1 Verify that session file is exist
if sessionFilePath == "":
raise IOError('"' + sessionFilePath + '" is not exist.')
# 2.2 Read the given file into "session" variable
with open(sessionFilePath, "r", encoding="utf-8") as sessionFile:
session = sessionFile.read()
# 2.3 Open Chrome browser
browser = webdriver.Chrome()
# 2.4 Open Web Whatsapp
browser.get("https://web.whatsapp.com/")
# 2.5 Wait for Web Whatsapp to be loaded properly
_wait_for_presence_of_an_element(browser, QR_CODE)
# 2.6 Execute javascript in browser to inject
# session by using variable "session"
print("Injecting session...")
browser.execute_script(INJECT_SESSION, session)
# 2.7 Refresh the page
browser.refresh()
# 2.8 Ask for user to enter any key to close browser
input("Press enter to close browser.")
#Output : python session_generator.py session.wa
[END]
|
Share WhatsApp Web without Scanning QR code using Python
|
https://www.geeksforgeeks.org/share-whatsapp-web-without-scanning-qr-code-using-python/
|
from session import *
import sys
# Take session file path as command line
# argument and passed to following method
sessionFilePath = sys.argv[1]
sessionOpener(sessionFilePath)
|
#Output : python session_generator.py session.wa
|
Share WhatsApp Web without Scanning QR code using Python
from session import *
import sys
# Take session file path as command line
# argument and passed to following method
sessionFilePath = sys.argv[1]
sessionOpener(sessionFilePath)
#Output : python session_generator.py session.wa
[END]
|
Automate WhatsApp Messages With Python using Pywhatkit module
|
https://www.geeksforgeeks.org/automate-whatsapp-messages-with-python-using-pywhatkit-module/
|
import pywhatkit
pywhatkit.sendwhatmsg("+919xxxxxxxxx", "Geeks For Geeks!", 18, 30)
|
#Output : pip install pywhatkit
|
Automate WhatsApp Messages With Python using Pywhatkit module
import pywhatkit
pywhatkit.sendwhatmsg("+919xxxxxxxxx", "Geeks For Geeks!", 18, 30)
#Output : pip install pywhatkit
[END]
|
How to Send Automated Email Messages in Python
|
https://www.geeksforgeeks.org/how-to-send-automated-email-messages-in-python/
|
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
|
#Output : pip install schedule
|
How to Send Automated Email Messages in Python
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
#Output : pip install schedule
[END]
|
How to Send Automated Email Messages in Python
|
https://www.geeksforgeeks.org/how-to-send-automated-email-messages-in-python/
|
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.ehlo()
smtp.starttls()
smtp.login("[email protected]", "Your Password")
|
#Output : pip install schedule
|
How to Send Automated Email Messages in Python
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.ehlo()
smtp.starttls()
smtp.login("[email protected]", "Your Password")
#Output : pip install schedule
[END]
|
How to Send Automated Email Messages in Python
|
https://www.geeksforgeeks.org/how-to-send-automated-email-messages-in-python/
|
msg = MIMEMultipart()
msg["Subject"] = subject
msg.attach(MIMEText(text))
|
#Output : pip install schedule
|
How to Send Automated Email Messages in Python
msg = MIMEMultipart()
msg["Subject"] = subject
msg.attach(MIMEText(text))
#Output : pip install schedule
[END]
|
How to Send Automated Email Messages in Python
|
https://www.geeksforgeeks.org/how-to-send-automated-email-messages-in-python/
|
img_data = open(one_img, "rb").read()
msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))
|
#Output : pip install schedule
|
How to Send Automated Email Messages in Python
img_data = open(one_img, "rb").read()
msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))
#Output : pip install schedule
[END]
|
How to Send Automated Email Messages in Python
|
https://www.geeksforgeeks.org/how-to-send-automated-email-messages-in-python/
|
with open(one_attachment, "rb") as f:
file = MIMEApplication(f.read(), name=os.path.basename(one_attachment))
file[
"Content-Disposition"
] = f'attachment; \
filename="{os.path.basename(one_attachment)}"'
msg.attach(file)
|
#Output : pip install schedule
|
How to Send Automated Email Messages in Python
with open(one_attachment, "rb") as f:
file = MIMEApplication(f.read(), name=os.path.basename(one_attachment))
file[
"Content-Disposition"
] = f'attachment; \
filename="{os.path.basename(one_attachment)}"'
msg.attach(file)
#Output : pip install schedule
[END]
|
How to Send Automated Email Messages in Python
|
https://www.geeksforgeeks.org/how-to-send-automated-email-messages-in-python/
|
to = ["[email protected]", "[email protected]", "[email protected]"]
smtp.sendmail(from_addr="Your Login Email", to_addrs=to, msg=msg.as_string())
smtp.quit()
|
#Output : pip install schedule
|
How to Send Automated Email Messages in Python
to = ["[email protected]", "[email protected]", "[email protected]"]
smtp.sendmail(from_addr="Your Login Email", to_addrs=to, msg=msg.as_string())
smtp.quit()
#Output : pip install schedule
[END]
|
How to Send Automated Email Messages in Python
|
https://www.geeksforgeeks.org/how-to-send-automated-email-messages-in-python/
|
# Import the following module
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
# initialize connection to our
# email server, we will use gmail here
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.ehlo()
smtp.starttls()
# Login with your email and password
smtp.login("Your Email", "Your Password")
# send our email message 'msg' to our boss
def message(subject="Python Notification", text="", img=None, attachment=None):
# build message contents
msg = MIMEMultipart()
# Add Subject
msg["Subject"] = subject
# Add text contents
msg.attach(MIMEText(text))
# Check if we have anything
# given in the img parameter
if img is not None:
# Check whether we have the lists of images or not!
if type(img) is not list:
# if it isn't a list, make it one
img = [img]
# Now iterate through our list
for one_img in img:
# read the image binary data
img_data = open(one_img, "rb").read()
# Attach the image data to MIMEMultipart
# using MIMEImage, we add the given filename use os.basename
msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))
# We do the same for
# attachments as we did for images
if attachment is not None:
# Check whether we have the
# lists of attachments or not!
if type(attachment) is not list:
# if it isn't a list, make it one
attachment = [attachment]
for one_attachment in attachment:
with open(one_attachment, "rb") as f:
# Read in the attachment
# using MIMEApplication
file = MIMEApplication(f.read(), name=os.path.basename(one_attachment))
file[
"Content-Disposition"
] = f'attachment;\
filename="{os.path.basename(one_attachment)}"'
# At last, Add the attachment to our message object
msg.attach(file)
return msg
# Call the message function
msg = message(
"Good!",
"Hi there!",
r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
r"C:\Users\Dell\Desktop\slack.py",
)
# Make a list of emails, where you wanna send mail
to = ["[email protected]", "[email protected]", "[email protected]"]
# Provide some data to the sendmail function!
smtp.sendmail(from_addr="[email protected]", to_addrs=to, msg=msg.as_string())
# Finally, don't forget to close the connection
smtp.quit()
|
#Output : pip install schedule
|
How to Send Automated Email Messages in Python
# Import the following module
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
# initialize connection to our
# email server, we will use gmail here
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.ehlo()
smtp.starttls()
# Login with your email and password
smtp.login("Your Email", "Your Password")
# send our email message 'msg' to our boss
def message(subject="Python Notification", text="", img=None, attachment=None):
# build message contents
msg = MIMEMultipart()
# Add Subject
msg["Subject"] = subject
# Add text contents
msg.attach(MIMEText(text))
# Check if we have anything
# given in the img parameter
if img is not None:
# Check whether we have the lists of images or not!
if type(img) is not list:
# if it isn't a list, make it one
img = [img]
# Now iterate through our list
for one_img in img:
# read the image binary data
img_data = open(one_img, "rb").read()
# Attach the image data to MIMEMultipart
# using MIMEImage, we add the given filename use os.basename
msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))
# We do the same for
# attachments as we did for images
if attachment is not None:
# Check whether we have the
# lists of attachments or not!
if type(attachment) is not list:
# if it isn't a list, make it one
attachment = [attachment]
for one_attachment in attachment:
with open(one_attachment, "rb") as f:
# Read in the attachment
# using MIMEApplication
file = MIMEApplication(f.read(), name=os.path.basename(one_attachment))
file[
"Content-Disposition"
] = f'attachment;\
filename="{os.path.basename(one_attachment)}"'
# At last, Add the attachment to our message object
msg.attach(file)
return msg
# Call the message function
msg = message(
"Good!",
"Hi there!",
r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
r"C:\Users\Dell\Desktop\slack.py",
)
# Make a list of emails, where you wanna send mail
to = ["[email protected]", "[email protected]", "[email protected]"]
# Provide some data to the sendmail function!
smtp.sendmail(from_addr="[email protected]", to_addrs=to, msg=msg.as_string())
# Finally, don't forget to close the connection
smtp.quit()
#Output : pip install schedule
[END]
|
How to Send Automated Email Messages in Python
|
https://www.geeksforgeeks.org/how-to-send-automated-email-messages-in-python/
|
import schedule
import time
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
# send our email message 'msg' to our boss
def message(subject="Python Notification", text="", img=None, attachment=None):
# build message contents
msg = MIMEMultipart()
# Add Subject
msg["Subject"] = subject
# Add text contents
msg.attach(MIMEText(text))
# Check if we have anything
# given in the img parameter
if img is not None:
# Check whether we have the
# lists of images or not!
if type(img) is not list:
# if it isn't a list, make it one
img = [img]
# Now iterate through our list
for one_img in img:
# read the image binary data
img_data = open(one_img, "rb").read()
# Attach the image data to MIMEMultipart
# using MIMEImage,
# we add the given filename use os.basename
msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))
# We do the same for attachments
# as we did for images
if attachment is not None:
# Check whether we have the
# lists of attachments or not!
if type(attachment) is not list:
# if it isn't a list, make it one
attachment = [attachment]
for one_attachment in attachment:
with open(one_attachment, "rb") as f:
# Read in the attachment using MIMEApplication
file = MIMEApplication(f.read(), name=os.path.basename(one_attachment))
file[
"Content-Disposition"
] = f'attachment;\
filename="{os.path.basename(one_attachment)}"'
# At last, Add the attachment to our message object
msg.attach(file)
return msg
def mail():
# initialize connection to our email server,
# we will use gmail here
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.ehlo()
smtp.starttls()
# Login with your email and password
smtp.login("Email", "Password")
# Call the message function
msg = message(
"Good!",
"Hi there!",
r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
r"C:\Users\Dell\Desktop\slack.py",
)
# Make a list of emails, where you wanna send mail
to = ["[email protected]", "[email protected]", "[email protected]"]
# Provide some data to the sendmail function!
smtp.sendmail(from_addr="[email protected]", to_addrs=to, msg=msg.as_string())
# Finally, don't forget to close the connection
smtp.quit()
schedule.every(2).seconds.do(mail)
schedule.every(10).minutes.do(mail)
schedule.every().hour.do(mail)
schedule.every().day.at("10:30").do(mail)
schedule.every(5).to(10).minutes.do(mail)
schedule.every().monday.do(mail)
schedule.every().wednesday.at("13:15").do(mail)
schedule.every().minute.at(":17").do(mail)
while True:
schedule.run_pending()
time.sleep(1)
|
#Output : pip install schedule
|
How to Send Automated Email Messages in Python
import schedule
import time
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
import smtplib
import os
# send our email message 'msg' to our boss
def message(subject="Python Notification", text="", img=None, attachment=None):
# build message contents
msg = MIMEMultipart()
# Add Subject
msg["Subject"] = subject
# Add text contents
msg.attach(MIMEText(text))
# Check if we have anything
# given in the img parameter
if img is not None:
# Check whether we have the
# lists of images or not!
if type(img) is not list:
# if it isn't a list, make it one
img = [img]
# Now iterate through our list
for one_img in img:
# read the image binary data
img_data = open(one_img, "rb").read()
# Attach the image data to MIMEMultipart
# using MIMEImage,
# we add the given filename use os.basename
msg.attach(MIMEImage(img_data, name=os.path.basename(one_img)))
# We do the same for attachments
# as we did for images
if attachment is not None:
# Check whether we have the
# lists of attachments or not!
if type(attachment) is not list:
# if it isn't a list, make it one
attachment = [attachment]
for one_attachment in attachment:
with open(one_attachment, "rb") as f:
# Read in the attachment using MIMEApplication
file = MIMEApplication(f.read(), name=os.path.basename(one_attachment))
file[
"Content-Disposition"
] = f'attachment;\
filename="{os.path.basename(one_attachment)}"'
# At last, Add the attachment to our message object
msg.attach(file)
return msg
def mail():
# initialize connection to our email server,
# we will use gmail here
smtp = smtplib.SMTP("smtp.gmail.com", 587)
smtp.ehlo()
smtp.starttls()
# Login with your email and password
smtp.login("Email", "Password")
# Call the message function
msg = message(
"Good!",
"Hi there!",
r"C:\Users\Dell\Downloads\Garbage\Cartoon.jpg",
r"C:\Users\Dell\Desktop\slack.py",
)
# Make a list of emails, where you wanna send mail
to = ["[email protected]", "[email protected]", "[email protected]"]
# Provide some data to the sendmail function!
smtp.sendmail(from_addr="[email protected]", to_addrs=to, msg=msg.as_string())
# Finally, don't forget to close the connection
smtp.quit()
schedule.every(2).seconds.do(mail)
schedule.every(10).minutes.do(mail)
schedule.every().hour.do(mail)
schedule.every().day.at("10:30").do(mail)
schedule.every(5).to(10).minutes.do(mail)
schedule.every().monday.do(mail)
schedule.every().wednesday.at("13:15").do(mail)
schedule.every().minute.at(":17").do(mail)
while True:
schedule.run_pending()
time.sleep(1)
#Output : pip install schedule
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
import shutil
from datetime import date
import os
import sys
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
import shutil
from datetime import date
import os
import sys
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
today = date.today()
date_format = today.strftime("%d_%b_%Y_")
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
today = date.today()
date_format = today.strftime("%d_%b_%Y_")
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
src_dir = src_dir + src_file_name
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
src_dir = src_dir + src_file_name
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
os.chdir(sys.path[0])
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
os.chdir(sys.path[0])
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
if not src_file_name:
print("Please give atleast the Source File Name")
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
if not src_file_name:
print("Please give atleast the Source File Name")
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
if src_file_name and dst_file_name and src_dir and dst_dir:
src_dir = src_dir + src_file_name
dst_dir = dst_dir + dst_file_name
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
if src_file_name and dst_file_name and src_dir and dst_dir:
src_dir = src_dir + src_file_name
dst_dir = dst_dir + dst_file_name
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
elif dst_file_name is None or not dst_file_name:??????????????????????????????????????????dst_file_name = src_file_name?????????????????????????????
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
elif dst_file_name is None or not dst_file_name:??????????????????????????????????????????dst_file_name = src_file_name?????????????????????????????
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
elif dst_file_name.isspace():????????????????????????????????????dst_file_name = src_file_name???????????????????????????????
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
elif dst_file_name.isspace():????????????????????????????????????dst_file_name = src_file_name???????????????????????????????
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
else:????????????????????????????????????dst_dir = dst_dir+d
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
else:????????????????????????????????????dst_dir = dst_dir+d
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
shutil.copy2(src_dir, dst_dir)
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
shutil.copy2(src_dir, dst_dir)
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automate backup with Python Script
|
https://www.geeksforgeeks.org/automate-backup-with-python-script/
|
# Import the following modules
import shutil
from datetime import date
import os
import sys
# When there is need, just change the directory
os.chdir(sys.path[0])
# Function for performing the
# backup of the files and folders
def take_backup(src_file_name, dst_file_name=None, src_dir="", dst_dir=""):
try:
# Extract the today's date
today = date.today()
date_format = today.strftime("%d_%b_%Y_")
# Make the source directory,
# where we wanna backup our files
src_dir = src_dir + src_file_name
# If user not enter any source file,
# then just give the error message...
if not src_file_name:
print("Please give atleast the Source File Name")
exit()
try:
# If user provides all the inputs
if src_file_name and dst_file_name and src_dir and dst_dir:
src_dir = src_dir + src_file_name
dst_dir = dst_dir + dst_file_name
# When User Enter Either
# 'None' or empty String ('')
elif dst_file_name is None or not dst_file_name:
dst_file_name = src_file_name
dst_dir = dst_dir + date_format + dst_file_name
# When user Enter an empty
# string with one or more spaces (' ')
elif dst_file_name.isspace():
dst_file_name = src_file_name
dst_dir = dst_dir + date_format + dst_file_name
# When user Enter an a
# name for the backup copy
else:
dst_dir = dst_dir + date_format + dst_file_name
# Now, just copy the files
# from source to destination
shutil.copy2(src_dir, dst_dir)
print("Backup Successful!")
except FileNotFoundError:
print(
"File does not exists!,\
please give the complete path"
)
# When we need to backup the folders only...
except PermissionError:
dst_dir = dst_dir + date_format + dst_file_name
# Copy the whole folder
# from source to destination
shutil.copytree(src_file_name, dst_dir)
# Call the function
take_backup("GFG.txt")
|
#Output : shutil.copytree(src_file_name, dst_dir)
|
Automate backup with Python Script
# Import the following modules
import shutil
from datetime import date
import os
import sys
# When there is need, just change the directory
os.chdir(sys.path[0])
# Function for performing the
# backup of the files and folders
def take_backup(src_file_name, dst_file_name=None, src_dir="", dst_dir=""):
try:
# Extract the today's date
today = date.today()
date_format = today.strftime("%d_%b_%Y_")
# Make the source directory,
# where we wanna backup our files
src_dir = src_dir + src_file_name
# If user not enter any source file,
# then just give the error message...
if not src_file_name:
print("Please give atleast the Source File Name")
exit()
try:
# If user provides all the inputs
if src_file_name and dst_file_name and src_dir and dst_dir:
src_dir = src_dir + src_file_name
dst_dir = dst_dir + dst_file_name
# When User Enter Either
# 'None' or empty String ('')
elif dst_file_name is None or not dst_file_name:
dst_file_name = src_file_name
dst_dir = dst_dir + date_format + dst_file_name
# When user Enter an empty
# string with one or more spaces (' ')
elif dst_file_name.isspace():
dst_file_name = src_file_name
dst_dir = dst_dir + date_format + dst_file_name
# When user Enter an a
# name for the backup copy
else:
dst_dir = dst_dir + date_format + dst_file_name
# Now, just copy the files
# from source to destination
shutil.copy2(src_dir, dst_dir)
print("Backup Successful!")
except FileNotFoundError:
print(
"File does not exists!,\
please give the complete path"
)
# When we need to backup the folders only...
except PermissionError:
dst_dir = dst_dir + date_format + dst_file_name
# Copy the whole folder
# from source to destination
shutil.copytree(src_file_name, dst_dir)
# Call the function
take_backup("GFG.txt")
#Output : shutil.copytree(src_file_name, dst_dir)
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
class Square:
def __init__(self, side):
"""creates a square having the given side"""
self.side = side
def area(self):
"""returns area of the square"""
return self.side**2
def perimeter(self):
"""returns perimeter of the square"""
return 4 * self.side
def __repr__(self):
"""declares how a Square object should be printed"""
s = (
"Square with side = "
+ str(self.side)
+ "\n"
+ "Area = "
+ str(self.area())
+ "\n"
+ "Perimeter = "
+ str(self.perimeter())
)
return s
if __name__ == "__main__":
# read input from the user
side = int(input("enter the side length to create a Square: "))
# create a square with the provided side
square = Square(side)
# print the created square
print(square)
|
#Output : ---Software_Testing
|
Automated software testing with Python
class Square:
def __init__(self, side):
"""creates a square having the given side"""
self.side = side
def area(self):
"""returns area of the square"""
return self.side**2
def perimeter(self):
"""returns perimeter of the square"""
return 4 * self.side
def __repr__(self):
"""declares how a Square object should be printed"""
s = (
"Square with side = "
+ str(self.side)
+ "\n"
+ "Area = "
+ str(self.area())
+ "\n"
+ "Perimeter = "
+ str(self.perimeter())
)
return s
if __name__ == "__main__":
# read input from the user
side = int(input("enter the side length to create a Square: "))
# create a square with the provided side
square = Square(side)
# print the created square
print(square)
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
def test_area(self):
# testing the method Square.area().
sq = Square(2) # creates a Square of side 2 units.
# test if the area of the above square is 4 units,
# display an error message if it's not.
self.assertEqual(
sq.area(), 4, f"Area is shown {sq.area()} for side = {sq.side} units"
)
|
#Output : ---Software_Testing
|
Automated software testing with Python
def test_area(self):
# testing the method Square.area().
sq = Square(2) # creates a Square of side 2 units.
# test if the area of the above square is 4 units,
# display an error message if it's not.
self.assertEqual(
sq.area(), 4, f"Area is shown {sq.area()} for side = {sq.side} units"
)
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
if __name__ == "__main__":
unittest.main()
|
#Output : ---Software_Testing
|
Automated software testing with Python
if __name__ == "__main__":
unittest.main()
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
import unittest
from .. import app
class TestSum(unittest.TestCase):
def test_area(self):
sq = app.Square(2)
self.assertEqual(sq.area(), 4, f"Area is shown {sq.area()} rather than 9")
if __name__ == "__main__":
unittest.main()
|
#Output : ---Software_Testing
|
Automated software testing with Python
import unittest
from .. import app
class TestSum(unittest.TestCase):
def test_area(self):
sq = app.Square(2)
self.assertEqual(sq.area(), 4, f"Area is shown {sq.area()} rather than 9")
if __name__ == "__main__":
unittest.main()
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
import unittest
from .. import app
class TestSum(unittest.TestCase):
def test_area(self):
sq = app.Square(2)
self.assertEqual(sq.area(), 4, f"Area is shown {sq.area()} rather than 9")
def test_area_negative(self):
sq = app.Square(-3)
self.assertEqual(sq.area(), -1, f"Area is shown {sq.area()} rather than -1")
def test_perimeter(self):
sq = app.Square(5)
self.assertEqual(
sq.perimeter(), 20, f"Perimeter is {sq.perimeter()} rather than 20"
)
def test_perimeter_negative(self):
sq = app.Square(-6)
self.assertEqual(
sq.perimeter(), -1, f"Perimeter is {sq.perimeter()} rather than -1"
)
if __name__ == "__main__":
unittest.main()
|
#Output : ---Software_Testing
|
Automated software testing with Python
import unittest
from .. import app
class TestSum(unittest.TestCase):
def test_area(self):
sq = app.Square(2)
self.assertEqual(sq.area(), 4, f"Area is shown {sq.area()} rather than 9")
def test_area_negative(self):
sq = app.Square(-3)
self.assertEqual(sq.area(), -1, f"Area is shown {sq.area()} rather than -1")
def test_perimeter(self):
sq = app.Square(5)
self.assertEqual(
sq.perimeter(), 20, f"Perimeter is {sq.perimeter()} rather than 20"
)
def test_perimeter_negative(self):
sq = app.Square(-6)
self.assertEqual(
sq.perimeter(), -1, f"Perimeter is {sq.perimeter()} rather than -1"
)
if __name__ == "__main__":
unittest.main()
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
from .. import app??????def test_file1_area():????????????????????????sq = app.Square(2)????????????????????????ass"area for side {sq.side} units is {sq.area()}"??def test_file1_perimeter():????????sq = app.Square(-1)????????assert sq.perimeter() == -1,????????????????f'perimeter is shown {sq.perimeter()} rather than -1'
|
#Output : ---Software_Testing
|
Automated software testing with Python
from .. import app??????def test_file1_area():????????????????????????sq = app.Square(2)????????????????????????ass"area for side {sq.side} units is {sq.area()}"??def test_file1_perimeter():????????sq = app.Square(-1)????????assert sq.perimeter() == -1,????????????????f'perimeter is shown {sq.perimeter()} rather than -1'
#Output : ---Software_Testing
[END]
|
Automated software testing with Python
|
https://www.geeksforgeeks.org/automated-software-testing-with-python/
|
# @pytest.mark.<tag_name>@pytest.mark.area??????????????????????????????def test_file1_area():????????????????????????sq = app.Square(2)???????????"area for side {sq.side} units is {sq.area()}"
|
#Output : ---Software_Testing
|
Automated software testing with Python
# @pytest.mark.<tag_name>@pytest.mark.area??????????????????????????????def test_file1_area():????????????????????????sq = app.Square(2)???????????"area for side {sq.side} units is {sq.area()}"
#Output : ---Software_Testing
[END]
|
Hotword detection with Python
|
https://www.geeksforgeeks.org/hotword-detection-with-python/
|
from snowboy import snowboydecode
|
#Output : sudo apt-get update
|
Hotword detection with Python
from snowboy import snowboydecode
#Output : sudo apt-get update
[END]
|
Hotword detection with Python
|
https://www.geeksforgeeks.org/hotword-detection-with-python/
|
from snowboy import snowboydecoder
def detected_callback():
print("hotword detected")
# do your task here or call other program.
detector = snowboydecoder.HotwordDetector("hotword.pmdl", sensitivity=0.5, audio_gain=1)
detector.start(detected_callback)
|
#Output : sudo apt-get update
|
Hotword detection with Python
from snowboy import snowboydecoder
def detected_callback():
print("hotword detected")
# do your task here or call other program.
detector = snowboydecoder.HotwordDetector("hotword.pmdl", sensitivity=0.5, audio_gain=1)
detector.start(detected_callback)
#Output : sudo apt-get update
[END]
|
Automate linkedin connections using Python
|
https://www.geeksforgeeks.org/automate-linkedin-connections-using-python/
|
# connect python with webbrowser-chrome
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyautogui as pag
def login():
# Getting the login element
username = driver.find_element_by_id("login-email")
# Sending the keys for username
username.send_keys("username")
# Getting the password element
password = driver.find_element_by_id("login-password")
# Sending the keys for password
password.send_keys("password")
# Getting the tag for submit button
driver.find_element_by_id("login-submit").click()
def goto_network():
driver.find_element_by_id("mynetwork-tab-icon").click()
def send_requests():
# Number of requests you want to send
n = input("Number of requests: ")
for i in range(0, n):
# position(in px) of connection button
pag.click(880, 770)
print("Done !")
def main():
# url of LinkedIn
url = "http://linkedin.com/"
# url of LinkedIn network page
network_url = "http://linkedin.com / mynetwork/"
# path to browser web driver
driver = webdriver.Chrome("C:\\Program Files\\Web Driver\\chromedriver.exe")
driver.get(url)
# Driver's code
if __name__ == __main__:
main()
|
#Output : pip install selenium
|
Automate linkedin connections using Python
# connect python with webbrowser-chrome
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import pyautogui as pag
def login():
# Getting the login element
username = driver.find_element_by_id("login-email")
# Sending the keys for username
username.send_keys("username")
# Getting the password element
password = driver.find_element_by_id("login-password")
# Sending the keys for password
password.send_keys("password")
# Getting the tag for submit button
driver.find_element_by_id("login-submit").click()
def goto_network():
driver.find_element_by_id("mynetwork-tab-icon").click()
def send_requests():
# Number of requests you want to send
n = input("Number of requests: ")
for i in range(0, n):
# position(in px) of connection button
pag.click(880, 770)
print("Done !")
def main():
# url of LinkedIn
url = "http://linkedin.com/"
# url of LinkedIn network page
network_url = "http://linkedin.com / mynetwork/"
# path to browser web driver
driver = webdriver.Chrome("C:\\Program Files\\Web Driver\\chromedriver.exe")
driver.get(url)
# Driver's code
if __name__ == __main__:
main()
#Output : pip install selenium
[END]
|
Create Table Using Tkinter
|
https://www.geeksforgeeks.org/create-table-using-tkinter/
|
# Python program to create a table
from tkinter import *
class Table:
def __init__(self, root):
# code for creating table
for i in range(total_rows):
for j in range(total_columns):
self.e = Entry(root, width=20, fg="blue", font=("Arial", 16, "bold"))
self.e.grid(row=i, column=j)
self.e.insert(END, lst[i][j])
# take the data
lst = [
(1, "Raj", "Mumbai", 19),
(2, "Aaryan", "Pune", 18),
(3, "Vaishnavi", "Mumbai", 20),
(4, "Rachna", "Mumbai", 21),
(5, "Shubham", "Delhi", 21),
]
# find total number of rows and
# columns in list
total_rows = len(lst)
total_columns = len(lst[0])
# create root window
root = Tk()
t = Table(root)
root.mainloop()
|
#Output : for i in range(5):
|
Create Table Using Tkinter
# Python program to create a table
from tkinter import *
class Table:
def __init__(self, root):
# code for creating table
for i in range(total_rows):
for j in range(total_columns):
self.e = Entry(root, width=20, fg="blue", font=("Arial", 16, "bold"))
self.e.grid(row=i, column=j)
self.e.insert(END, lst[i][j])
# take the data
lst = [
(1, "Raj", "Mumbai", 19),
(2, "Aaryan", "Pune", 18),
(3, "Vaishnavi", "Mumbai", 20),
(4, "Rachna", "Mumbai", 21),
(5, "Shubham", "Delhi", 21),
]
# find total number of rows and
# columns in list
total_rows = len(lst)
total_columns = len(lst[0])
# create root window
root = Tk()
t = Table(root)
root.mainloop()
#Output : for i in range(5):
[END]
|
Image Viewer App in Python using Tkinter
|
https://www.geeksforgeeks.org/image-viewer-app-in-python-using-tkinter/
|
# importing the tkinter module and PIL that
# is pillow module
from tkinter import *
from PIL import ImageTk, Image
# Calling the Tk (The initial constructor of tkinter)
root = Tk()
# We will make the title of our app as Image Viewer
root.title("Image Viewer")
# The geometry of the box which will be displayed
# on the screen
root.geometry("700x700")
# Adding the images using the pillow module which
# has a class ImageTk We can directly add the
# photos in the tkinter folder or we have to
# give a proper path for the images
image_no_1 = ImageTk.PhotoImage(Image.open("Sample.png"))
image_no_2 = ImageTk.PhotoImage(Image.open("sample.png"))
image_no_3 = ImageTk.PhotoImage(Image.open("Sample.png"))
image_no_4 = ImageTk.PhotoImage(Image.open("sample.png"))
# List of the images so that we traverse the list
List_images = [image_no_1, image_no_2, image_no_3, image_no_4]
label = Label(image=image_no_1)
# We have to show the box so this below line is needed
label.grid(row=1, column=0, columnspan=3)
# We will have three button back ,forward and exit
button_back = Button(root, text="Back", command=back, state=DISABLED)
# root.quit for closing the app
button_exit = Button(root, text="Exit", command=root.quit)
button_forward = Button(root, text="Forward", command=lambda: forward(1))
# grid function is for placing the buttons in the frame
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_forward.grid(row=5, column=2)
root.mainloop()
|
#Output : pip install tkinter
|
Image Viewer App in Python using Tkinter
# importing the tkinter module and PIL that
# is pillow module
from tkinter import *
from PIL import ImageTk, Image
# Calling the Tk (The initial constructor of tkinter)
root = Tk()
# We will make the title of our app as Image Viewer
root.title("Image Viewer")
# The geometry of the box which will be displayed
# on the screen
root.geometry("700x700")
# Adding the images using the pillow module which
# has a class ImageTk We can directly add the
# photos in the tkinter folder or we have to
# give a proper path for the images
image_no_1 = ImageTk.PhotoImage(Image.open("Sample.png"))
image_no_2 = ImageTk.PhotoImage(Image.open("sample.png"))
image_no_3 = ImageTk.PhotoImage(Image.open("Sample.png"))
image_no_4 = ImageTk.PhotoImage(Image.open("sample.png"))
# List of the images so that we traverse the list
List_images = [image_no_1, image_no_2, image_no_3, image_no_4]
label = Label(image=image_no_1)
# We have to show the box so this below line is needed
label.grid(row=1, column=0, columnspan=3)
# We will have three button back ,forward and exit
button_back = Button(root, text="Back", command=back, state=DISABLED)
# root.quit for closing the app
button_exit = Button(root, text="Exit", command=root.quit)
button_forward = Button(root, text="Forward", command=lambda: forward(1))
# grid function is for placing the buttons in the frame
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_forward.grid(row=5, column=2)
root.mainloop()
#Output : pip install tkinter
[END]
|
Image Viewer App in Python using Tkinter
|
https://www.geeksforgeeks.org/image-viewer-app-in-python-using-tkinter/
|
def forward(img_no):
# GLobal variable so that we can have
# access and change the variable
# whenever needed
global label
global button_forward
global button_back
global button_exit
label.grid_forget()
# This is for clearing the screen so that
# our next image can pop up
label = Label(image=List_images[img_no - 1])
# as the list starts from 0 so we are
# subtracting one
label.grid(row=1, column=0, columnspan=3)
button_for = Button(root, text="forward", command=lambda: forward(img_no + 1))
# img_no+1 as we want the next image to pop up
if img_no == 4:
button_forward = Button(root, text="Forward", state=DISABLED)
# img_no-1 as we want previous image when we click
# back button
button_back = Button(root, text="Back", command=lambda: back(img_no - 1))
# Placing the button in new grid
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_for.grid(row=5, column=2)
|
#Output : pip install tkinter
|
Image Viewer App in Python using Tkinter
def forward(img_no):
# GLobal variable so that we can have
# access and change the variable
# whenever needed
global label
global button_forward
global button_back
global button_exit
label.grid_forget()
# This is for clearing the screen so that
# our next image can pop up
label = Label(image=List_images[img_no - 1])
# as the list starts from 0 so we are
# subtracting one
label.grid(row=1, column=0, columnspan=3)
button_for = Button(root, text="forward", command=lambda: forward(img_no + 1))
# img_no+1 as we want the next image to pop up
if img_no == 4:
button_forward = Button(root, text="Forward", state=DISABLED)
# img_no-1 as we want previous image when we click
# back button
button_back = Button(root, text="Back", command=lambda: back(img_no - 1))
# Placing the button in new grid
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_for.grid(row=5, column=2)
#Output : pip install tkinter
[END]
|
Image Viewer App in Python using Tkinter
|
https://www.geeksforgeeks.org/image-viewer-app-in-python-using-tkinter/
|
def back(img_no):
# We will have global variable to access these
# variable and change whenever needed
global label
global button_forward
global button_back
global button_exit
label.grid_forget()
# for clearing the image for new image to pop up
label = Label(image=List_images[img_no - 1])
label.grid(row=1, column=0, columnspan=3)
button_forward = Button(root, text="forward", command=lambda: forward(img_no + 1))
button_back = Button(root, text="Back", command=lambda: back(img_no - 1))
print(img_no)
# whenever the first image will be there we will
# have the back button disabled
if img_no == 1:
button_back = Button(root, Text="Back", state=DISABLED)
label.grid(row=1, column=0, columnspan=3)
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_for.grid(row=5, column=2)
|
#Output : pip install tkinter
|
Image Viewer App in Python using Tkinter
def back(img_no):
# We will have global variable to access these
# variable and change whenever needed
global label
global button_forward
global button_back
global button_exit
label.grid_forget()
# for clearing the image for new image to pop up
label = Label(image=List_images[img_no - 1])
label.grid(row=1, column=0, columnspan=3)
button_forward = Button(root, text="forward", command=lambda: forward(img_no + 1))
button_back = Button(root, text="Back", command=lambda: back(img_no - 1))
print(img_no)
# whenever the first image will be there we will
# have the back button disabled
if img_no == 1:
button_back = Button(root, Text="Back", state=DISABLED)
label.grid(row=1, column=0, columnspan=3)
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_for.grid(row=5, column=2)
#Output : pip install tkinter
[END]
|
Image Viewer App in Python using Tkinter
|
https://www.geeksforgeeks.org/image-viewer-app-in-python-using-tkinter/
|
# importing the tkinter module and PIL
# that is pillow module
from tkinter import *
from PIL import ImageTk, Image
def forward(img_no):
# GLobal variable so that we can have
# access and change the variable
# whenever needed
global label
global button_forward
global button_back
global button_exit
label.grid_forget()
# This is for clearing the screen so that
# our next image can pop up
label = Label(image=List_images[img_no - 1])
# as the list starts from 0 so we are
# subtracting one
label.grid(row=1, column=0, columnspan=3)
button_for = Button(root, text="forward", command=lambda: forward(img_no + 1))
# img_no+1 as we want the next image to pop up
if img_no == 4:
button_forward = Button(root, text="Forward", state=DISABLED)
# img_no-1 as we want previous image when we click
# back button
button_back = Button(root, text="Back", command=lambda: back(img_no - 1))
# Placing the button in new grid
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_for.grid(row=5, column=2)
def back(img_no):
# We will have global variable to access these
# variable and change whenever needed
global label
global button_forward
global button_back
global button_exit
label.grid_forget()
# for clearing the image for new image to pop up
label = Label(image=List_images[img_no - 1])
label.grid(row=1, column=0, columnspan=3)
button_forward = Button(root, text="forward", command=lambda: forward(img_no + 1))
button_back = Button(root, text="Back", command=lambda: back(img_no - 1))
print(img_no)
# whenever the first image will be there we will
# have the back button disabled
if img_no == 1:
button_back = Button(root, Text="Back", state=DISABLED)
label.grid(row=1, column=0, columnspan=3)
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_for.grid(row=5, column=2)
# Calling the Tk (The initial constructor of tkinter)
root = Tk()
# We will make the title of our app as Image Viewer
root.title("Image Viewer")
# The geometry of the box which will be displayed
# on the screen
root.geometry("700x700")
# Adding the images using the pillow module which
# has a class ImageTk We can directly add the
# photos in the tkinter folder or we have to
# give a proper path for the images
image_no_1 = ImageTk.PhotoImage(Image.open("Sample.png"))
image_no_2 = ImageTk.PhotoImage(Image.open("sample.png"))
image_no_3 = ImageTk.PhotoImage(Image.open("Sample.png"))
image_no_4 = ImageTk.PhotoImage(Image.open("sample.png"))
# List of the images so that we traverse the list
List_images = [image_no_1, image_no_2, image_no_3, image_no_4]
label = Label(image=image_no_1)
# We have to show the box so this below line is needed
label.grid(row=1, column=0, columnspan=3)
# We will have three button back ,forward and exit
button_back = Button(root, text="Back", command=back, state=DISABLED)
# root.quit for closing the app
button_exit = Button(root, text="Exit", command=root.quit)
button_forward = Button(root, text="Forward", command=lambda: forward(1))
# grid function is for placing the buttons in the frame
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_forward.grid(row=5, column=2)
root.mainloop()
|
#Output : pip install tkinter
|
Image Viewer App in Python using Tkinter
# importing the tkinter module and PIL
# that is pillow module
from tkinter import *
from PIL import ImageTk, Image
def forward(img_no):
# GLobal variable so that we can have
# access and change the variable
# whenever needed
global label
global button_forward
global button_back
global button_exit
label.grid_forget()
# This is for clearing the screen so that
# our next image can pop up
label = Label(image=List_images[img_no - 1])
# as the list starts from 0 so we are
# subtracting one
label.grid(row=1, column=0, columnspan=3)
button_for = Button(root, text="forward", command=lambda: forward(img_no + 1))
# img_no+1 as we want the next image to pop up
if img_no == 4:
button_forward = Button(root, text="Forward", state=DISABLED)
# img_no-1 as we want previous image when we click
# back button
button_back = Button(root, text="Back", command=lambda: back(img_no - 1))
# Placing the button in new grid
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_for.grid(row=5, column=2)
def back(img_no):
# We will have global variable to access these
# variable and change whenever needed
global label
global button_forward
global button_back
global button_exit
label.grid_forget()
# for clearing the image for new image to pop up
label = Label(image=List_images[img_no - 1])
label.grid(row=1, column=0, columnspan=3)
button_forward = Button(root, text="forward", command=lambda: forward(img_no + 1))
button_back = Button(root, text="Back", command=lambda: back(img_no - 1))
print(img_no)
# whenever the first image will be there we will
# have the back button disabled
if img_no == 1:
button_back = Button(root, Text="Back", state=DISABLED)
label.grid(row=1, column=0, columnspan=3)
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_for.grid(row=5, column=2)
# Calling the Tk (The initial constructor of tkinter)
root = Tk()
# We will make the title of our app as Image Viewer
root.title("Image Viewer")
# The geometry of the box which will be displayed
# on the screen
root.geometry("700x700")
# Adding the images using the pillow module which
# has a class ImageTk We can directly add the
# photos in the tkinter folder or we have to
# give a proper path for the images
image_no_1 = ImageTk.PhotoImage(Image.open("Sample.png"))
image_no_2 = ImageTk.PhotoImage(Image.open("sample.png"))
image_no_3 = ImageTk.PhotoImage(Image.open("Sample.png"))
image_no_4 = ImageTk.PhotoImage(Image.open("sample.png"))
# List of the images so that we traverse the list
List_images = [image_no_1, image_no_2, image_no_3, image_no_4]
label = Label(image=image_no_1)
# We have to show the box so this below line is needed
label.grid(row=1, column=0, columnspan=3)
# We will have three button back ,forward and exit
button_back = Button(root, text="Back", command=back, state=DISABLED)
# root.quit for closing the app
button_exit = Button(root, text="Exit", command=root.quit)
button_forward = Button(root, text="Forward", command=lambda: forward(1))
# grid function is for placing the buttons in the frame
button_back.grid(row=5, column=0)
button_exit.grid(row=5, column=1)
button_forward.grid(row=5, column=2)
root.mainloop()
#Output : pip install tkinter
[END]
|
Create GUI for Downloading Youtube Video using Python
|
https://www.geeksforgeeks.org/create-gui-for-downloading-youtube-video-using-python/
|
# Importing necessary packages
import tkinter as tk
from tkinter import *
from pytube import YouTube
from tkinter import messagebox, filedialog
# Defining CreateWidgets() function
# to create necessary tkinter widgets
def Widgets():
head_label = Label(
root,
text="YouTube Video Downloader Using Tkinter",
padx=15,
pady=15,
font="SegoeUI 14",
bg="palegreen1",
fg="red",
)
head_label.grid(row=1, column=1, pady=10, padx=5, columnspan=3)
link_label = Label(root, text="YouTube link :", bg="salmon", pady=5, padx=5)
link_label.grid(row=2, column=0, pady=5, padx=5)
root.linkText = Entry(root, width=35, textvariable=video_Link, font="Arial 14")
root.linkText.grid(row=2, column=1, pady=5, padx=5, columnspan=2)
destination_label = Label(root, text="Destination :", bg="salmon", pady=5, padx=9)
destination_label.grid(row=3, column=0, pady=5, padx=5)
root.destinationText = Entry(
root, width=27, textvariable=download_Path, font="Arial 14"
)
root.destinationText.grid(row=3, column=1, pady=5, padx=5)
browse_B = Button(
root, text="Browse", command=Browse, width=10, bg="bisque", relief=GROOVE
)
browse_B.grid(row=3, column=2, pady=1, padx=1)
Download_B = Button(
root,
text="Download Video",
command=Download,
width=20,
bg="thistle1",
pady=10,
padx=15,
relief=GROOVE,
font="Georgia, 13",
)
Download_B.grid(row=4, column=1, pady=20, padx=20)
# Defining Browse() to select a
# destination folder to save the video
def Browse():
# Presenting user with a pop-up for
# directory selection. initialdir
# argument is optional Retrieving the
# user-input destination directory and
# storing it in downloadDirectory
download_Directory = filedialog.askdirectory(
initialdir="YOUR DIRECTORY PATH", title="Save Video"
)
# Displaying the directory in the directory
# textbox
download_Path.set(download_Directory)
# Defining Download() to download the video
def Download():
# getting user-input Youtube Link
Youtube_link = video_Link.get()
# select the optimal location for
# saving file's
download_Folder = download_Path.get()
# Creating object of YouTube()
getVideo = YouTube(Youtube_link)
# Getting all the available streams of the
# youtube video and selecting the first
# from the
videoStream = getVideo.streams.first()
# Downloading the video to destination
# directory
videoStream.download(download_Folder)
# Displaying the message
messagebox.showinfo("SUCCESSFULLY", "DOWNLOADED AND SAVED IN\n" + download_Folder)
# Creating object of tk class
root = tk.Tk()
# Setting the title, background color
# and size of the tkinter window and
# disabling the resizing property
root.geometry("520x280")
root.resizable(False, False)
root.title("YouTube Video Downloader")
root.config(background="PaleGreen1")
# Creating the tkinter Variables
video_Link = StringVar()
download_Path = StringVar()
# Calling the Widgets() function
Widgets()
# Defining infinite loop to run
# application
root.mainloop()
|
#Output : pip install pytube3
|
Create GUI for Downloading Youtube Video using Python
# Importing necessary packages
import tkinter as tk
from tkinter import *
from pytube import YouTube
from tkinter import messagebox, filedialog
# Defining CreateWidgets() function
# to create necessary tkinter widgets
def Widgets():
head_label = Label(
root,
text="YouTube Video Downloader Using Tkinter",
padx=15,
pady=15,
font="SegoeUI 14",
bg="palegreen1",
fg="red",
)
head_label.grid(row=1, column=1, pady=10, padx=5, columnspan=3)
link_label = Label(root, text="YouTube link :", bg="salmon", pady=5, padx=5)
link_label.grid(row=2, column=0, pady=5, padx=5)
root.linkText = Entry(root, width=35, textvariable=video_Link, font="Arial 14")
root.linkText.grid(row=2, column=1, pady=5, padx=5, columnspan=2)
destination_label = Label(root, text="Destination :", bg="salmon", pady=5, padx=9)
destination_label.grid(row=3, column=0, pady=5, padx=5)
root.destinationText = Entry(
root, width=27, textvariable=download_Path, font="Arial 14"
)
root.destinationText.grid(row=3, column=1, pady=5, padx=5)
browse_B = Button(
root, text="Browse", command=Browse, width=10, bg="bisque", relief=GROOVE
)
browse_B.grid(row=3, column=2, pady=1, padx=1)
Download_B = Button(
root,
text="Download Video",
command=Download,
width=20,
bg="thistle1",
pady=10,
padx=15,
relief=GROOVE,
font="Georgia, 13",
)
Download_B.grid(row=4, column=1, pady=20, padx=20)
# Defining Browse() to select a
# destination folder to save the video
def Browse():
# Presenting user with a pop-up for
# directory selection. initialdir
# argument is optional Retrieving the
# user-input destination directory and
# storing it in downloadDirectory
download_Directory = filedialog.askdirectory(
initialdir="YOUR DIRECTORY PATH", title="Save Video"
)
# Displaying the directory in the directory
# textbox
download_Path.set(download_Directory)
# Defining Download() to download the video
def Download():
# getting user-input Youtube Link
Youtube_link = video_Link.get()
# select the optimal location for
# saving file's
download_Folder = download_Path.get()
# Creating object of YouTube()
getVideo = YouTube(Youtube_link)
# Getting all the available streams of the
# youtube video and selecting the first
# from the
videoStream = getVideo.streams.first()
# Downloading the video to destination
# directory
videoStream.download(download_Folder)
# Displaying the message
messagebox.showinfo("SUCCESSFULLY", "DOWNLOADED AND SAVED IN\n" + download_Folder)
# Creating object of tk class
root = tk.Tk()
# Setting the title, background color
# and size of the tkinter window and
# disabling the resizing property
root.geometry("520x280")
root.resizable(False, False)
root.title("YouTube Video Downloader")
root.config(background="PaleGreen1")
# Creating the tkinter Variables
video_Link = StringVar()
download_Path = StringVar()
# Calling the Widgets() function
Widgets()
# Defining infinite loop to run
# application
root.mainloop()
#Output : pip install pytube3
[END]
|
Create a GUI to extract Lyrics from song Using Python
|
https://www.geeksforgeeks.org/create-a-gui-to-extract-lyrics-from-song-using-python/
|
# importing modules
from lyrics_extractor import SongLyrics
# pass the GCS_API_KEY, GCS_ENGINE_ID
extract_lyrics = SongLyrics("AIzaSewfsdfsdfOq0oTixw", "frewrewrfsac")
extract_lyrics.get_lyrics("Tujhse Naraz Nahi Zindagi Lyrics")
|
#Output : pip install lyrics-extractor
|
Create a GUI to extract Lyrics from song Using Python
# importing modules
from lyrics_extractor import SongLyrics
# pass the GCS_API_KEY, GCS_ENGINE_ID
extract_lyrics = SongLyrics("AIzaSewfsdfsdfOq0oTixw", "frewrewrfsac")
extract_lyrics.get_lyrics("Tujhse Naraz Nahi Zindagi Lyrics")
#Output : pip install lyrics-extractor
[END]
|
Create a GUI to extract Lyrics from song Using Python
|
https://www.geeksforgeeks.org/create-a-gui-to-extract-lyrics-from-song-using-python/
|
# import modules
from tkinter import *
from lyrics_extractor import SongLyrics
# user defined function
def get_lyrics():
extract_lyrics = SongLyrics("Aerwerwefwdssdj-nvN3Oq0oTixw", "werwerewcxzcsda")
temp = extract_lyrics.get_lyrics(str(e.get()))
res = temp["lyrics"]
result.set(res)
# object of tkinter
# and background set to light grey
master = Tk()
master.configure(bg="light grey")
# Variable Classes in tkinter
result = StringVar()
# Creating label for each information
# name using widget Label
Label(master, text="Enter Song name : ", bg="light grey").grid(row=0, sticky=W)
Label(master, text="Result :", bg="light grey").grid(row=3, sticky=W)
# Creating label for class variable
# name using widget Entry
Label(master, text="", textvariable=result, bg="light grey").grid(
row=3, column=1, sticky=W
)
e = Entry(master, width=50)
e.grid(row=0, column=1)
# creating a button using the widget
b = Button(master, text="Show", command=get_lyrics, bg="Blue")
b.grid(
row=0,
column=2,
columnspan=2,
rowspan=2,
padx=5,
pady=5,
)
mainloop()
|
#Output : pip install lyrics-extractor
|
Create a GUI to extract Lyrics from song Using Python
# import modules
from tkinter import *
from lyrics_extractor import SongLyrics
# user defined function
def get_lyrics():
extract_lyrics = SongLyrics("Aerwerwefwdssdj-nvN3Oq0oTixw", "werwerewcxzcsda")
temp = extract_lyrics.get_lyrics(str(e.get()))
res = temp["lyrics"]
result.set(res)
# object of tkinter
# and background set to light grey
master = Tk()
master.configure(bg="light grey")
# Variable Classes in tkinter
result = StringVar()
# Creating label for each information
# name using widget Label
Label(master, text="Enter Song name : ", bg="light grey").grid(row=0, sticky=W)
Label(master, text="Result :", bg="light grey").grid(row=3, sticky=W)
# Creating label for class variable
# name using widget Entry
Label(master, text="", textvariable=result, bg="light grey").grid(
row=3, column=1, sticky=W
)
e = Entry(master, width=50)
e.grid(row=0, column=1)
# creating a button using the widget
b = Button(master, text="Show", command=get_lyrics, bg="Blue")
b.grid(
row=0,
column=2,
columnspan=2,
rowspan=2,
padx=5,
pady=5,
)
mainloop()
#Output : pip install lyrics-extractor
[END]
|
Application to get live USD/INR rate Using Python
|
https://www.geeksforgeeks.org/application-to-get-live-usd-inr-rate-using-python/
|
# Import required modules
import requests
from bs4 import BeautifulSoup
|
#Output : pip install bs4
|
Application to get live USD/INR rate Using Python
# Import required modules
import requests
from bs4 import BeautifulSoup
#Output : pip install bs4
[END]
|
Application to get live USD/INR rate Using Python
|
https://www.geeksforgeeks.org/application-to-get-live-usd-inr-rate-using-python/
|
# Function to extract html data
def getdata(url):
r = requests.get(url)
return r.text
|
#Output : pip install bs4
|
Application to get live USD/INR rate Using Python
# Function to extract html data
def getdata(url):
r = requests.get(url)
return r.text
#Output : pip install bs4
[END]
|
Application to get live USD/INR rate Using Python
|
https://www.geeksforgeeks.org/application-to-get-live-usd-inr-rate-using-python/
|
# Extract and converthtmldata = getdata("https://finance.yahoo.com/quote/usdinr=X?ltr=1")soup = BeautifulSoup(htmldata, 'html.parser')result = (soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)")
|
#Output : pip install bs4
|
Application to get live USD/INR rate Using Python
# Extract and converthtmldata = getdata("https://finance.yahoo.com/quote/usdinr=X?ltr=1")soup = BeautifulSoup(htmldata, 'html.parser')result = (soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)")
#Output : pip install bs4
[END]
|
Application to get live USD/INR rate Using Python
|
https://www.geeksforgeeks.org/application-to-get-live-usd-inr-rate-using-python/
|
mydatastr = ""
# Filter converted data
for table in soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)"):
mydatastr += table.get_text()
# Display output
print(mydatastr)
|
#Output : pip install bs4
|
Application to get live USD/INR rate Using Python
mydatastr = ""
# Filter converted data
for table in soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)"):
mydatastr += table.get_text()
# Display output
print(mydatastr)
#Output : pip install bs4
[END]
|
Application to get live USD/INR rate Using Python
|
https://www.geeksforgeeks.org/application-to-get-live-usd-inr-rate-using-python/
|
# Import required modules
from tkinter import *
import requests
from bs4 import BeautifulSoup
# user defined function
# to extract currency details
def getdata(url):
r = requests.get(url)
return r.text
# Function to compute and display currency details
def get_info():
try:
htmldata = getdata("https://finance.yahoo.com/quote/usdinr=X?ltr=1")
soup = BeautifulSoup(htmldata, "html.parser")
mydatastr = ""
for table in soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)"):
mydatastr += table.get_text()
list_data = mydatastr.split()
temp = list_data[0].split("-")
rate.set(temp[0])
inc.set(temp[1])
per_rate.set(list_data[1])
time.set(list_data[3])
result.set("success")
except:
result.set("Opps! something wrong")
# Driver Code
# Create tkinter object
master = Tk()
# Set background color
master.configure(bg="light grey")
# Variable Classes in tkinter
result = StringVar()
rate = StringVar()
per_rate = StringVar()
time = StringVar()
inc = StringVar()
# Creating label for each information
Label(master, text="Status :", bg="light grey").grid(row=2, sticky=W)
Label(master, text="Current rate of INR :", bg="light grey").grid(row=3, sticky=W)
Label(master, text="Increase/decrease by :", bg="light grey").grid(row=4, sticky=W)
Label(master, text="Rate change :", bg="light grey").grid(row=5, sticky=W)
Label(master, text="Rate of time :", bg="light grey").grid(row=6, sticky=W)
# Creating label for class variable
Label(master, text="", textvariable=result, bg="light grey").grid(
row=2, column=1, sticky=W
)
Label(master, text="", textvariable=rate, bg="light grey").grid(
row=3, column=1, sticky=W
)
Label(master, text="", textvariable=inc, bg="light grey").grid(
row=4, column=1, sticky=W
)
Label(master, text="", textvariable=per_rate, bg="light grey").grid(
row=5, column=1, sticky=W
)
Label(master, text="", textvariable=time, bg="light grey").grid(
row=6, column=1, sticky=W
)
# Create submit button
b = Button(master, text="Show", command=get_info, bg="Blue").grid(row=0)
mainloop()
|
#Output : pip install bs4
|
Application to get live USD/INR rate Using Python
# Import required modules
from tkinter import *
import requests
from bs4 import BeautifulSoup
# user defined function
# to extract currency details
def getdata(url):
r = requests.get(url)
return r.text
# Function to compute and display currency details
def get_info():
try:
htmldata = getdata("https://finance.yahoo.com/quote/usdinr=X?ltr=1")
soup = BeautifulSoup(htmldata, "html.parser")
mydatastr = ""
for table in soup.find_all("div", class_="D(ib) Va(m) Maw(65%) Ov(h)"):
mydatastr += table.get_text()
list_data = mydatastr.split()
temp = list_data[0].split("-")
rate.set(temp[0])
inc.set(temp[1])
per_rate.set(list_data[1])
time.set(list_data[3])
result.set("success")
except:
result.set("Opps! something wrong")
# Driver Code
# Create tkinter object
master = Tk()
# Set background color
master.configure(bg="light grey")
# Variable Classes in tkinter
result = StringVar()
rate = StringVar()
per_rate = StringVar()
time = StringVar()
inc = StringVar()
# Creating label for each information
Label(master, text="Status :", bg="light grey").grid(row=2, sticky=W)
Label(master, text="Current rate of INR :", bg="light grey").grid(row=3, sticky=W)
Label(master, text="Increase/decrease by :", bg="light grey").grid(row=4, sticky=W)
Label(master, text="Rate change :", bg="light grey").grid(row=5, sticky=W)
Label(master, text="Rate of time :", bg="light grey").grid(row=6, sticky=W)
# Creating label for class variable
Label(master, text="", textvariable=result, bg="light grey").grid(
row=2, column=1, sticky=W
)
Label(master, text="", textvariable=rate, bg="light grey").grid(
row=3, column=1, sticky=W
)
Label(master, text="", textvariable=inc, bg="light grey").grid(
row=4, column=1, sticky=W
)
Label(master, text="", textvariable=per_rate, bg="light grey").grid(
row=5, column=1, sticky=W
)
Label(master, text="", textvariable=time, bg="light grey").grid(
row=6, column=1, sticky=W
)
# Create submit button
b = Button(master, text="Show", command=get_info, bg="Blue").grid(row=0)
mainloop()
#Output : pip install bs4
[END]
|
Build an Application for Screen Rotation Using Python
|
https://www.geeksforgeeks.org/build-an-application-for-screen-rotation-using-python/
|
# Import required module
import rotatescreen
|
#Output : pip install rotate-screen
|
Build an Application for Screen Rotation Using Python
# Import required module
import rotatescreen
#Output : pip install rotate-screen
[END]
|
Build an Application for Screen Rotation Using Python
|
https://www.geeksforgeeks.org/build-an-application-for-screen-rotation-using-python/
|
# Accessing the main screen
rotate_screen = rotatescreen.get_primary_display()
|
#Output : pip install rotate-screen
|
Build an Application for Screen Rotation Using Python
# Accessing the main screen
rotate_screen = rotatescreen.get_primary_display()
#Output : pip install rotate-screen
[END]
|
Build an Application for Screen Rotation Using Python
|
https://www.geeksforgeeks.org/build-an-application-for-screen-rotation-using-python/
|
# Methods to change orientation
# for landscape
rotate_screen.set_landscape()
# portrait at left
rotate_screen.set_portrait_flipped()
# landscape at down
rotate_screen.set_landscape_flipped()
# portrait at right
rotate_screen.set_portrait()
|
#Output : pip install rotate-screen
|
Build an Application for Screen Rotation Using Python
# Methods to change orientation
# for landscape
rotate_screen.set_landscape()
# portrait at left
rotate_screen.set_portrait_flipped()
# landscape at down
rotate_screen.set_landscape_flipped()
# portrait at right
rotate_screen.set_portrait()
#Output : pip install rotate-screen
[END]
|
Build an Application for Screen Rotation Using Python
|
https://www.geeksforgeeks.org/build-an-application-for-screen-rotation-using-python/
|
# Import required modules
from tkinter import *
import rotatescreen
# User defined function
# for rotating screen
def Screen_rotation(temp):
screen = rotatescreen.get_primary_display()
if temp == "up":
screen.set_landscape()
elif temp == "right":
screen.set_portrait_flipped()
elif temp == "down":
screen.set_landscape_flipped()
elif temp == "left":
screen.set_portrait()
# Creating tkinter object
master = Tk()
master.geometry("100x100")
master.title("Screen Rotation")
master.configure(bg="light grey")
# Variable classes in tkinter
result = StringVar()
# Creating buttons to change orientation
Button(master, text="Up", command=lambda: Screen_rotation("up"), bg="white").grid(
row=0, column=3
)
Button(master, text="Right", command=lambda: Screen_rotation("right"), bg="white").grid(
row=1, column=6
)
Button(master, text="Left", command=lambda: Screen_rotation("left"), bg="white").grid(
row=1, column=2
)
Button(master, text="Down", command=lambda: Screen_rotation("down"), bg="white").grid(
row=3, column=3
)
mainloop()
# this code belongs to Satyam kumar (ksatyam858)
|
#Output : pip install rotate-screen
|
Build an Application for Screen Rotation Using Python
# Import required modules
from tkinter import *
import rotatescreen
# User defined function
# for rotating screen
def Screen_rotation(temp):
screen = rotatescreen.get_primary_display()
if temp == "up":
screen.set_landscape()
elif temp == "right":
screen.set_portrait_flipped()
elif temp == "down":
screen.set_landscape_flipped()
elif temp == "left":
screen.set_portrait()
# Creating tkinter object
master = Tk()
master.geometry("100x100")
master.title("Screen Rotation")
master.configure(bg="light grey")
# Variable classes in tkinter
result = StringVar()
# Creating buttons to change orientation
Button(master, text="Up", command=lambda: Screen_rotation("up"), bg="white").grid(
row=0, column=3
)
Button(master, text="Right", command=lambda: Screen_rotation("right"), bg="white").grid(
row=1, column=6
)
Button(master, text="Left", command=lambda: Screen_rotation("left"), bg="white").grid(
row=1, column=2
)
Button(master, text="Down", command=lambda: Screen_rotation("down"), bg="white").grid(
row=3, column=3
)
mainloop()
# this code belongs to Satyam kumar (ksatyam858)
#Output : pip install rotate-screen
[END]
|
Text detection using Python
|
https://www.geeksforgeeks.org/text-detection-using-python/
|
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tkinter import *
import tkinter.messagebox
from nltk.sentiment.vader import SentimentIntensityAnalyzer
class analysis_text:
# Main function in program
def center(self, toplevel):
toplevel.update_idletasks()
w = toplevel.winfo_screenwidth()
h = toplevel.winfo_screenheight()
size = tuple(int(_) for _ in toplevel.geometry().split("+")[0].split("x"))
x = w / 2 - size[0] / 2
y = h / 2 - size[1] / 2
toplevel.geometry("%dx%d+%d+%d" % (size + (x, y)))
def callback(self):
if tkinter.messagebox.askokcancel("Quit", "Do you want to leave?"):
self.main.destroy()
def setResult(self, type, res):
# calculated comments in vader analysis
if type == "neg":
self.negativeLabel.configure(
text="you typed negative comment : " + str(res) + " % \n"
)
elif type == "neu":
self.neutralLabel.configure(
text="you typed comment : " + str(res) + " % \n"
)
elif type == "pos":
self.positiveLabel.configure(
text="you typed positive comment: " + str(res) + " % \n"
)
def runAnalysis(self):
sentences = []
sentences.append(self.line.get())
sid = SentimentIntensityAnalyzer()
for sentence in sentences:
# print(sentence)
ss = sid.polarity_scores(sentence)
if ss["compound"] >= 0.05:
self.normalLabel.configure(text=" you typed positive statement: ")
elif ss["compound"] <= -0.05:
self.normalLabel.configure(text=" you typed negative statement")
else:
self.normalLabel.configure(text=" you normal typed statement: ")
for k in sorted(ss):
self.setResult(k, ss[k])
print()
def editedText(self, event):
self.typedText.configure(text=self.line.get() + event.char)
def runByEnter(self, event):
self.runAnalysis()
def __init__(self):
# Create main window
self.main = Tk()
self.main.title("Text Detector system")
self.main.geometry("600x600")
self.main.resizable(width=FALSE, height=FALSE)
self.main.protocol("WM_DELETE_WINDOW", self.callback)
self.main.focus()
self.center(self.main)
# addition item on window
self.label1 = Label(text="type a text here :")
self.label1.pack()
# Add a hidden button Enter
self.line = Entry(self.main, width=70)
self.line.pack()
self.textLabel = Label(text="\n", font=("Helvetica", 15))
self.textLabel.pack()
self.typedText = Label(text="", fg="blue", font=("Helvetica", 20))
self.typedText.pack()
self.line.bind("<Key>", self.editedText)
self.line.bind("<Return>", self.runByEnter)
self.result = Label(text="\n", font=("Helvetica", 15))
self.result.pack()
self.negativeLabel = Label(text="", fg="red", font=("Helvetica", 20))
self.negativeLabel.pack()
self.neutralLabel = Label(text="", font=("Helvetica", 20))
self.neutralLabel.pack()
self.positiveLabel = Label(text="", fg="green", font=("Helvetica", 20))
self.positiveLabel.pack()
self.normalLabel = Label(text="", fg="red", font=("Helvetica", 20))
self.normalLabel.pack()
# Driver code
myanalysis = analysis_text()
mainloop()
|
#Output : conda install -c anaconda tk
|
Text detection using Python
import time
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tkinter import *
import tkinter.messagebox
from nltk.sentiment.vader import SentimentIntensityAnalyzer
class analysis_text:
# Main function in program
def center(self, toplevel):
toplevel.update_idletasks()
w = toplevel.winfo_screenwidth()
h = toplevel.winfo_screenheight()
size = tuple(int(_) for _ in toplevel.geometry().split("+")[0].split("x"))
x = w / 2 - size[0] / 2
y = h / 2 - size[1] / 2
toplevel.geometry("%dx%d+%d+%d" % (size + (x, y)))
def callback(self):
if tkinter.messagebox.askokcancel("Quit", "Do you want to leave?"):
self.main.destroy()
def setResult(self, type, res):
# calculated comments in vader analysis
if type == "neg":
self.negativeLabel.configure(
text="you typed negative comment : " + str(res) + " % \n"
)
elif type == "neu":
self.neutralLabel.configure(
text="you typed comment : " + str(res) + " % \n"
)
elif type == "pos":
self.positiveLabel.configure(
text="you typed positive comment: " + str(res) + " % \n"
)
def runAnalysis(self):
sentences = []
sentences.append(self.line.get())
sid = SentimentIntensityAnalyzer()
for sentence in sentences:
# print(sentence)
ss = sid.polarity_scores(sentence)
if ss["compound"] >= 0.05:
self.normalLabel.configure(text=" you typed positive statement: ")
elif ss["compound"] <= -0.05:
self.normalLabel.configure(text=" you typed negative statement")
else:
self.normalLabel.configure(text=" you normal typed statement: ")
for k in sorted(ss):
self.setResult(k, ss[k])
print()
def editedText(self, event):
self.typedText.configure(text=self.line.get() + event.char)
def runByEnter(self, event):
self.runAnalysis()
def __init__(self):
# Create main window
self.main = Tk()
self.main.title("Text Detector system")
self.main.geometry("600x600")
self.main.resizable(width=FALSE, height=FALSE)
self.main.protocol("WM_DELETE_WINDOW", self.callback)
self.main.focus()
self.center(self.main)
# addition item on window
self.label1 = Label(text="type a text here :")
self.label1.pack()
# Add a hidden button Enter
self.line = Entry(self.main, width=70)
self.line.pack()
self.textLabel = Label(text="\n", font=("Helvetica", 15))
self.textLabel.pack()
self.typedText = Label(text="", fg="blue", font=("Helvetica", 20))
self.typedText.pack()
self.line.bind("<Key>", self.editedText)
self.line.bind("<Return>", self.runByEnter)
self.result = Label(text="\n", font=("Helvetica", 15))
self.result.pack()
self.negativeLabel = Label(text="", fg="red", font=("Helvetica", 20))
self.negativeLabel.pack()
self.neutralLabel = Label(text="", font=("Helvetica", 20))
self.neutralLabel.pack()
self.positiveLabel = Label(text="", fg="green", font=("Helvetica", 20))
self.positiveLabel.pack()
self.normalLabel = Label(text="", fg="red", font=("Helvetica", 20))
self.normalLabel.pack()
# Driver code
myanalysis = analysis_text()
mainloop()
#Output : conda install -c anaconda tk
[END]
|
Make Notepad using Tkinter
|
https://www.geeksforgeeks.org/make-notepad-using-tkinter/
|
import tkinter
import os
from tkinter import *
# To get the space above for message
from tkinter.messagebox import *
# To get the dialog box to open when required
from tkinter.filedialog import *
|
#Output : pip install python-tk
|
Make Notepad using Tkinter
import tkinter
import os
from tkinter import *
# To get the space above for message
from tkinter.messagebox import *
# To get the dialog box to open when required
from tkinter.filedialog import *
#Output : pip install python-tk
[END]
|
Make Notepad using Tkinter
|
https://www.geeksforgeeks.org/make-notepad-using-tkinter/
|
# Add controls(widget)
self.__thisTextArea.grid(sticky=N + E + S + W)
# To open new file
self.__thisFileMenu.add_command(label="New", command=self.__newFile)
# To open a already existing file
self.__thisFileMenu.add_command(label="Open", command=self.__openFile)
# To save current file
self.__thisFileMenu.add_command(label="Save", command=self.__saveFile)
# To create a line in the dialog
self.__thisFileMenu.add_separator()
# To terminate
self.__thisFileMenu.add_command(label="Exit", command=self.__quitApplication)
self.__thisMenuBar.add_cascade(label="File", menu=self.__thisFileMenu)
# To give a feature of cut
self.__thisEditMenu.add_command(label="Cut", command=self.__cut)
# To give a feature of copy
self.__thisEditMenu.add_command(label="Copy", command=self.__copy)
# To give a feature of paste
self.__thisEditMenu.add_command(label="Paste", command=self.__paste)
# To give a feature of editing
self.__thisMenuBar.add_cascade(label="Edit", menu=self.__thisEditMenu)
# To create a feature of description of the notepad
self.__thisHelpMenu.add_command(label="About Notepad", command=self.__showAbout)
self.__thisMenuBar.add_cascade(label="Help", menu=self.__thisHelpMenu)
self.__root.config(menu=self.__thisMenuBar)
self.__thisScrollBar.pack(side=RIGHT, fill=Y)
# Scrollbar will adjust automatically
# according to the content
self.__thisScrollBar.config(command=self.__thisTextArea.yview)
self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
|
#Output : pip install python-tk
|
Make Notepad using Tkinter
# Add controls(widget)
self.__thisTextArea.grid(sticky=N + E + S + W)
# To open new file
self.__thisFileMenu.add_command(label="New", command=self.__newFile)
# To open a already existing file
self.__thisFileMenu.add_command(label="Open", command=self.__openFile)
# To save current file
self.__thisFileMenu.add_command(label="Save", command=self.__saveFile)
# To create a line in the dialog
self.__thisFileMenu.add_separator()
# To terminate
self.__thisFileMenu.add_command(label="Exit", command=self.__quitApplication)
self.__thisMenuBar.add_cascade(label="File", menu=self.__thisFileMenu)
# To give a feature of cut
self.__thisEditMenu.add_command(label="Cut", command=self.__cut)
# To give a feature of copy
self.__thisEditMenu.add_command(label="Copy", command=self.__copy)
# To give a feature of paste
self.__thisEditMenu.add_command(label="Paste", command=self.__paste)
# To give a feature of editing
self.__thisMenuBar.add_cascade(label="Edit", menu=self.__thisEditMenu)
# To create a feature of description of the notepad
self.__thisHelpMenu.add_command(label="About Notepad", command=self.__showAbout)
self.__thisMenuBar.add_cascade(label="Help", menu=self.__thisHelpMenu)
self.__root.config(menu=self.__thisMenuBar)
self.__thisScrollBar.pack(side=RIGHT, fill=Y)
# Scrollbar will adjust automatically
# according to the content
self.__thisScrollBar.config(command=self.__thisTextArea.yview)
self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
#Output : pip install python-tk
[END]
|
Make Notepad using Tkinter
|
https://www.geeksforgeeks.org/make-notepad-using-tkinter/
|
def __quitApplication(self):
self.__root.destroy()
# exit()
def __showAbout(self):
showinfo("Notepad", "Mrinal Verma")
def __openFile(self):
self.__file = askopenfilename(
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")],
)
if self.__file == "":
# no file to open
self.__file = None
else:
# try to open the file
# set the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
self.__thisTextArea.delete(1.0, END)
file = open(self.__file, "r")
self.__thisTextArea.insert(1.0, file.read())
file.close()
def __newFile(self):
self.__root.title("Untitled - Notepad")
self.__file = None
self.__thisTextArea.delete(1.0, END)
def __saveFile(self):
if self.__file == None:
# save as new file
self.__file = asksaveasfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")],
)
if self.__file == "":
self.__file = None
else:
# try to save the file
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
# change the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
else:
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
def __cut(self):
self.__thisTextArea.event_generate("<<Cut>>")
def __copy(self):
self.__thisTextArea.event_generate("<<Copy>>")
def __paste(self):
self.__thisTextArea.event_generate("<<Paste>>")
|
#Output : pip install python-tk
|
Make Notepad using Tkinter
def __quitApplication(self):
self.__root.destroy()
# exit()
def __showAbout(self):
showinfo("Notepad", "Mrinal Verma")
def __openFile(self):
self.__file = askopenfilename(
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")],
)
if self.__file == "":
# no file to open
self.__file = None
else:
# try to open the file
# set the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
self.__thisTextArea.delete(1.0, END)
file = open(self.__file, "r")
self.__thisTextArea.insert(1.0, file.read())
file.close()
def __newFile(self):
self.__root.title("Untitled - Notepad")
self.__file = None
self.__thisTextArea.delete(1.0, END)
def __saveFile(self):
if self.__file == None:
# save as new file
self.__file = asksaveasfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")],
)
if self.__file == "":
self.__file = None
else:
# try to save the file
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
# change the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
else:
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
def __cut(self):
self.__thisTextArea.event_generate("<<Cut>>")
def __copy(self):
self.__thisTextArea.event_generate("<<Copy>>")
def __paste(self):
self.__thisTextArea.event_generate("<<Paste>>")
#Output : pip install python-tk
[END]
|
Make Notepad using Tkinter
|
https://www.geeksforgeeks.org/make-notepad-using-tkinter/
|
import tkinter
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
class Notepad:
__root = Tk()
# default window width and height
__thisWidth = 300
__thisHeight = 300
__thisTextArea = Text(__root)
__thisMenuBar = Menu(__root)
__thisFileMenu = Menu(__thisMenuBar, tearoff=0)
__thisEditMenu = Menu(__thisMenuBar, tearoff=0)
__thisHelpMenu = Menu(__thisMenuBar, tearoff=0)
# To add scrollbar
__thisScrollBar = Scrollbar(__thisTextArea)
__file = None
def __init__(self, **kwargs):
# Set icon
try:
self.__root.wm_iconbitmap("Notepad.ico")
except:
pass
# Set window size (the default is 300x300)
try:
self.__thisWidth = kwargs["width"]
except KeyError:
pass
try:
self.__thisHeight = kwargs["height"]
except KeyError:
pass
# Set the window text
self.__root.title("Untitled - Notepad")
# Center the window
screenWidth = self.__root.winfo_screenwidth()
screenHeight = self.__root.winfo_screenheight()
# For left-align
left = (screenWidth / 2) - (self.__thisWidth / 2)
# For right-align
top = (screenHeight / 2) - (self.__thisHeight / 2)
# For top and bottom
self.__root.geometry(
"%dx%d+%d+%d" % (self.__thisWidth, self.__thisHeight, left, top)
)
# To make the textarea auto resizable
self.__root.grid_rowconfigure(0, weight=1)
self.__root.grid_columnconfigure(0, weight=1)
# Add controls (widget)
self.__thisTextArea.grid(sticky=N + E + S + W)
# To open new file
self.__thisFileMenu.add_command(label="New", command=self.__newFile)
# To open a already existing file
self.__thisFileMenu.add_command(label="Open", command=self.__openFile)
# To save current file
self.__thisFileMenu.add_command(label="Save", command=self.__saveFile)
# To create a line in the dialog
self.__thisFileMenu.add_separator()
self.__thisFileMenu.add_command(label="Exit", command=self.__quitApplication)
self.__thisMenuBar.add_cascade(label="File", menu=self.__thisFileMenu)
# To give a feature of cut
self.__thisEditMenu.add_command(label="Cut", command=self.__cut)
# to give a feature of copy
self.__thisEditMenu.add_command(label="Copy", command=self.__copy)
# To give a feature of paste
self.__thisEditMenu.add_command(label="Paste", command=self.__paste)
# To give a feature of editing
self.__thisMenuBar.add_cascade(label="Edit", menu=self.__thisEditMenu)
# To create a feature of description of the notepad
self.__thisHelpMenu.add_command(label="About Notepad", command=self.__showAbout)
self.__thisMenuBar.add_cascade(label="Help", menu=self.__thisHelpMenu)
self.__root.config(menu=self.__thisMenuBar)
self.__thisScrollBar.pack(side=RIGHT, fill=Y)
# Scrollbar will adjust automatically according to the content
self.__thisScrollBar.config(command=self.__thisTextArea.yview)
self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
def __quitApplication(self):
self.__root.destroy()
# exit()
def __showAbout(self):
showinfo("Notepad", "Mrinal Verma")
def __openFile(self):
self.__file = askopenfilename(
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")],
)
if self.__file == "":
# no file to open
self.__file = None
else:
# Try to open the file
# set the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
self.__thisTextArea.delete(1.0, END)
file = open(self.__file, "r")
self.__thisTextArea.insert(1.0, file.read())
file.close()
def __newFile(self):
self.__root.title("Untitled - Notepad")
self.__file = None
self.__thisTextArea.delete(1.0, END)
def __saveFile(self):
if self.__file == None:
# Save as new file
self.__file = asksaveasfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")],
)
if self.__file == "":
self.__file = None
else:
# Try to save the file
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
# Change the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
else:
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
def __cut(self):
self.__thisTextArea.event_generate("<<Cut>>")
def __copy(self):
self.__thisTextArea.event_generate("<<Copy>>")
def __paste(self):
self.__thisTextArea.event_generate("<<Paste>>")
def run(self):
# Run main application
self.__root.mainloop()
# Run main application
notepad = Notepad(width=600, height=400)
notepad.run()
|
#Output : pip install python-tk
|
Make Notepad using Tkinter
import tkinter
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
class Notepad:
__root = Tk()
# default window width and height
__thisWidth = 300
__thisHeight = 300
__thisTextArea = Text(__root)
__thisMenuBar = Menu(__root)
__thisFileMenu = Menu(__thisMenuBar, tearoff=0)
__thisEditMenu = Menu(__thisMenuBar, tearoff=0)
__thisHelpMenu = Menu(__thisMenuBar, tearoff=0)
# To add scrollbar
__thisScrollBar = Scrollbar(__thisTextArea)
__file = None
def __init__(self, **kwargs):
# Set icon
try:
self.__root.wm_iconbitmap("Notepad.ico")
except:
pass
# Set window size (the default is 300x300)
try:
self.__thisWidth = kwargs["width"]
except KeyError:
pass
try:
self.__thisHeight = kwargs["height"]
except KeyError:
pass
# Set the window text
self.__root.title("Untitled - Notepad")
# Center the window
screenWidth = self.__root.winfo_screenwidth()
screenHeight = self.__root.winfo_screenheight()
# For left-align
left = (screenWidth / 2) - (self.__thisWidth / 2)
# For right-align
top = (screenHeight / 2) - (self.__thisHeight / 2)
# For top and bottom
self.__root.geometry(
"%dx%d+%d+%d" % (self.__thisWidth, self.__thisHeight, left, top)
)
# To make the textarea auto resizable
self.__root.grid_rowconfigure(0, weight=1)
self.__root.grid_columnconfigure(0, weight=1)
# Add controls (widget)
self.__thisTextArea.grid(sticky=N + E + S + W)
# To open new file
self.__thisFileMenu.add_command(label="New", command=self.__newFile)
# To open a already existing file
self.__thisFileMenu.add_command(label="Open", command=self.__openFile)
# To save current file
self.__thisFileMenu.add_command(label="Save", command=self.__saveFile)
# To create a line in the dialog
self.__thisFileMenu.add_separator()
self.__thisFileMenu.add_command(label="Exit", command=self.__quitApplication)
self.__thisMenuBar.add_cascade(label="File", menu=self.__thisFileMenu)
# To give a feature of cut
self.__thisEditMenu.add_command(label="Cut", command=self.__cut)
# to give a feature of copy
self.__thisEditMenu.add_command(label="Copy", command=self.__copy)
# To give a feature of paste
self.__thisEditMenu.add_command(label="Paste", command=self.__paste)
# To give a feature of editing
self.__thisMenuBar.add_cascade(label="Edit", menu=self.__thisEditMenu)
# To create a feature of description of the notepad
self.__thisHelpMenu.add_command(label="About Notepad", command=self.__showAbout)
self.__thisMenuBar.add_cascade(label="Help", menu=self.__thisHelpMenu)
self.__root.config(menu=self.__thisMenuBar)
self.__thisScrollBar.pack(side=RIGHT, fill=Y)
# Scrollbar will adjust automatically according to the content
self.__thisScrollBar.config(command=self.__thisTextArea.yview)
self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
def __quitApplication(self):
self.__root.destroy()
# exit()
def __showAbout(self):
showinfo("Notepad", "Mrinal Verma")
def __openFile(self):
self.__file = askopenfilename(
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")],
)
if self.__file == "":
# no file to open
self.__file = None
else:
# Try to open the file
# set the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
self.__thisTextArea.delete(1.0, END)
file = open(self.__file, "r")
self.__thisTextArea.insert(1.0, file.read())
file.close()
def __newFile(self):
self.__root.title("Untitled - Notepad")
self.__file = None
self.__thisTextArea.delete(1.0, END)
def __saveFile(self):
if self.__file == None:
# Save as new file
self.__file = asksaveasfilename(
initialfile="Untitled.txt",
defaultextension=".txt",
filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")],
)
if self.__file == "":
self.__file = None
else:
# Try to save the file
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
# Change the window title
self.__root.title(os.path.basename(self.__file) + " - Notepad")
else:
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
def __cut(self):
self.__thisTextArea.event_generate("<<Cut>>")
def __copy(self):
self.__thisTextArea.event_generate("<<Copy>>")
def __paste(self):
self.__thisTextArea.event_generate("<<Paste>>")
def run(self):
# Run main application
self.__root.mainloop()
# Run main application
notepad = Notepad(width=600, height=400)
notepad.run()
#Output : pip install python-tk
[END]
|
Create a GUI for Weather Forecast using openweathermap API in Python
|
https://www.geeksforgeeks.org/create-a-gui-for-weather-forecast-using-openweathermap-api-in-python/
|
# python3 -- Weather Application using API
# importing the libraries
from tkinter import *
import requests
import json
import datetime
from PIL import ImageTk, Image
# necessary details
root = Tk()
root.title("Weather App")
root.geometry("450x700")
root["background"] = "white"
# Image
new = ImageTk.PhotoImage(Image.open("logo.png"))
panel = Label(root, image=new)
panel.place(x=0, y=520)
# Dates
dt = datetime.datetime.now()
date = Label(root, text=dt.strftime("%A--"), bg="white", font=("bold", 15))
date.place(x=5, y=130)
month = Label(root, text=dt.strftime("%m %B"), bg="white", font=("bold", 15))
month.place(x=100, y=130)
# Time
hour = Label(root, text=dt.strftime("%I : %M %p"), bg="white", font=("bold", 15))
hour.place(x=10, y=160)
# Theme for the respective time the application is used
if int((dt.strftime("%I"))) >= 8 & int((dt.strftime("%I"))) <= 5:
img = ImageTk.PhotoImage(Image.open("moon.png"))
panel = Label(root, image=img)
panel.place(x=210, y=200)
else:
img = ImageTk.PhotoImage(Image.open("sun.png"))
panel = Label(root, image=img)
panel.place(x=210, y=200)
# City Search
city_name = StringVar()
city_entry = Entry(root, textvariable=city_name, width=45)
city_entry.grid(row=1, column=0, ipady=10, stick=W + E + N + S)
def city_name():
# API Call
api_request = requests.get(
"https://api.openweathermap.org/data/2.5/weather?q="
+ city_entry.get()
+ "&units=metric&appid="
+ api_key
)
api = json.loads(api_request.content)
# Temperatures
y = api["main"]
current_temprature = y["temp"]
humidity = y["humidity"]
tempmin = y["temp_min"]
tempmax = y["temp_max"]
# Coordinates
x = api["coord"]
longtitude = x["lon"]
latitude = x["lat"]
# Country
z = api["sys"]
country = z["country"]
citi = api["name"]
# Adding the received info into the screen
lable_temp.configure(text=current_temprature)
lable_humidity.configure(text=humidity)
max_temp.configure(text=tempmax)
min_temp.configure(text=tempmin)
lable_lon.configure(text=longtitude)
lable_lat.configure(text=latitude)
lable_country.configure(text=country)
lable_citi.configure(text=citi)
# Search Bar and Button
city_nameButton = Button(root, text="Search", command=city_name)
city_nameButton.grid(row=1, column=1, padx=5, stick=W + E + N + S)
# Country Names and Coordinates
lable_citi = Label(root, text="...", width=0, bg="white", font=("bold", 15))
lable_citi.place(x=10, y=63)
lable_country = Label(root, text="...", width=0, bg="white", font=("bold", 15))
lable_country.place(x=135, y=63)
lable_lon = Label(root, text="...", width=0, bg="white", font=("Helvetica", 15))
lable_lon.place(x=25, y=95)
lable_lat = Label(root, text="...", width=0, bg="white", font=("Helvetica", 15))
lable_lat.place(x=95, y=95)
# Current Temperature
lable_temp = Label(
root, text="...", width=0, bg="white", font=("Helvetica", 110), fg="black"
)
lable_temp.place(x=18, y=220)
# Other temperature details
humi = Label(root, text="Humidity: ", width=0, bg="white", font=("bold", 15))
humi.place(x=3, y=400)
lable_humidity = Label(root, text="...", width=0, bg="white", font=("bold", 15))
lable_humidity.place(x=107, y=400)
maxi = Label(root, text="Max. Temp.: ", width=0, bg="white", font=("bold", 15))
maxi.place(x=3, y=430)
max_temp = Label(root, text="...", width=0, bg="white", font=("bold", 15))
max_temp.place(x=128, y=430)
mini = Label(root, text="Min. Temp.: ", width=0, bg="white", font=("bold", 15))
mini.place(x=3, y=460)
min_temp = Label(root, text="...", width=0, bg="white", font=("bold", 15))
min_temp.place(x=128, y=460)
# Note
note = Label(
root, text="All temperatures in degree celsius", bg="white", font=("italic", 10)
)
note.place(x=95, y=495)
root.mainloop()
|
#Output : pip install requests
|
Create a GUI for Weather Forecast using openweathermap API in Python
# python3 -- Weather Application using API
# importing the libraries
from tkinter import *
import requests
import json
import datetime
from PIL import ImageTk, Image
# necessary details
root = Tk()
root.title("Weather App")
root.geometry("450x700")
root["background"] = "white"
# Image
new = ImageTk.PhotoImage(Image.open("logo.png"))
panel = Label(root, image=new)
panel.place(x=0, y=520)
# Dates
dt = datetime.datetime.now()
date = Label(root, text=dt.strftime("%A--"), bg="white", font=("bold", 15))
date.place(x=5, y=130)
month = Label(root, text=dt.strftime("%m %B"), bg="white", font=("bold", 15))
month.place(x=100, y=130)
# Time
hour = Label(root, text=dt.strftime("%I : %M %p"), bg="white", font=("bold", 15))
hour.place(x=10, y=160)
# Theme for the respective time the application is used
if int((dt.strftime("%I"))) >= 8 & int((dt.strftime("%I"))) <= 5:
img = ImageTk.PhotoImage(Image.open("moon.png"))
panel = Label(root, image=img)
panel.place(x=210, y=200)
else:
img = ImageTk.PhotoImage(Image.open("sun.png"))
panel = Label(root, image=img)
panel.place(x=210, y=200)
# City Search
city_name = StringVar()
city_entry = Entry(root, textvariable=city_name, width=45)
city_entry.grid(row=1, column=0, ipady=10, stick=W + E + N + S)
def city_name():
# API Call
api_request = requests.get(
"https://api.openweathermap.org/data/2.5/weather?q="
+ city_entry.get()
+ "&units=metric&appid="
+ api_key
)
api = json.loads(api_request.content)
# Temperatures
y = api["main"]
current_temprature = y["temp"]
humidity = y["humidity"]
tempmin = y["temp_min"]
tempmax = y["temp_max"]
# Coordinates
x = api["coord"]
longtitude = x["lon"]
latitude = x["lat"]
# Country
z = api["sys"]
country = z["country"]
citi = api["name"]
# Adding the received info into the screen
lable_temp.configure(text=current_temprature)
lable_humidity.configure(text=humidity)
max_temp.configure(text=tempmax)
min_temp.configure(text=tempmin)
lable_lon.configure(text=longtitude)
lable_lat.configure(text=latitude)
lable_country.configure(text=country)
lable_citi.configure(text=citi)
# Search Bar and Button
city_nameButton = Button(root, text="Search", command=city_name)
city_nameButton.grid(row=1, column=1, padx=5, stick=W + E + N + S)
# Country Names and Coordinates
lable_citi = Label(root, text="...", width=0, bg="white", font=("bold", 15))
lable_citi.place(x=10, y=63)
lable_country = Label(root, text="...", width=0, bg="white", font=("bold", 15))
lable_country.place(x=135, y=63)
lable_lon = Label(root, text="...", width=0, bg="white", font=("Helvetica", 15))
lable_lon.place(x=25, y=95)
lable_lat = Label(root, text="...", width=0, bg="white", font=("Helvetica", 15))
lable_lat.place(x=95, y=95)
# Current Temperature
lable_temp = Label(
root, text="...", width=0, bg="white", font=("Helvetica", 110), fg="black"
)
lable_temp.place(x=18, y=220)
# Other temperature details
humi = Label(root, text="Humidity: ", width=0, bg="white", font=("bold", 15))
humi.place(x=3, y=400)
lable_humidity = Label(root, text="...", width=0, bg="white", font=("bold", 15))
lable_humidity.place(x=107, y=400)
maxi = Label(root, text="Max. Temp.: ", width=0, bg="white", font=("bold", 15))
maxi.place(x=3, y=430)
max_temp = Label(root, text="...", width=0, bg="white", font=("bold", 15))
max_temp.place(x=128, y=430)
mini = Label(root, text="Min. Temp.: ", width=0, bg="white", font=("bold", 15))
mini.place(x=3, y=460)
min_temp = Label(root, text="...", width=0, bg="white", font=("bold", 15))
min_temp.place(x=128, y=460)
# Note
note = Label(
root, text="All temperatures in degree celsius", bg="white", font=("italic", 10)
)
note.place(x=95, y=495)
root.mainloop()
#Output : pip install requests
[END]
|
Build a Voice Recorder GUI using Python
|
https://www.geeksforgeeks.org/build-a-voice-recorder-gui-using-python/
|
import sounddevice as sd
import soundfile as sf
from tkinter import *
def Voice_rec():
fs = 48000
# seconds
duration = 5
myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2)
sd.wait()
# Save as FLAC file at correct sampling rate
return sf.write("my_Audio_file.flac", myrecording, fs)
master = Tk()
Label(master, text=" Voice Recoder : ").grid(row=0, sticky=W, rowspan=5)
b = Button(master, text="Start", command=Voice_rec)
b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5)
mainloop()
|
#Output : pip install sounddevice
|
Build a Voice Recorder GUI using Python
import sounddevice as sd
import soundfile as sf
from tkinter import *
def Voice_rec():
fs = 48000
# seconds
duration = 5
myrecording = sd.rec(int(duration * fs), samplerate=fs, channels=2)
sd.wait()
# Save as FLAC file at correct sampling rate
return sf.write("my_Audio_file.flac", myrecording, fs)
master = Tk()
Label(master, text=" Voice Recoder : ").grid(row=0, sticky=W, rowspan=5)
b = Button(master, text="Start", command=Voice_rec)
b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5)
mainloop()
#Output : pip install sounddevice
[END]
|
Create a Sideshow application in Python
|
https://www.geeksforgeeks.org/create-a-sideshow-application-in-python/
|
# import required modules
import tkinter as tk
from tkinter import *
from PIL import Image
from PIL import ImageTk
|
#Output : pip install Pillow
|
Create a Sideshow application in Python
# import required modules
import tkinter as tk
from tkinter import *
from PIL import Image
from PIL import ImageTk
#Output : pip install Pillow
[END]
|
Create a Sideshow application in Python
|
https://www.geeksforgeeks.org/create-a-sideshow-application-in-python/
|
# adjust window
root = tk.Tk()
root.geometry("200x200")
# loading the images
img = ImageTk.PhotoImage(Image.open("photo1.png"))
img2 = ImageTk.PhotoImage(Image.open("photo2.png"))
img3 = ImageTk.PhotoImage(Image.open("photo3.png"))
l = Label()
l.pack()
|
#Output : pip install Pillow
|
Create a Sideshow application in Python
# adjust window
root = tk.Tk()
root.geometry("200x200")
# loading the images
img = ImageTk.PhotoImage(Image.open("photo1.png"))
img2 = ImageTk.PhotoImage(Image.open("photo2.png"))
img3 = ImageTk.PhotoImage(Image.open("photo3.png"))
l = Label()
l.pack()
#Output : pip install Pillow
[END]
|
Create a Sideshow application in Python
|
https://www.geeksforgeeks.org/create-a-sideshow-application-in-python/
|
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x + 1
root.after(2000, move)
# calling the function
move()
|
#Output : pip install Pillow
|
Create a Sideshow application in Python
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x + 1
root.after(2000, move)
# calling the function
move()
#Output : pip install Pillow
[END]
|
Create a Sideshow application in Python
|
https://www.geeksforgeeks.org/create-a-sideshow-application-in-python/
|
root.mainloop()
|
#Output : pip install Pillow
|
Create a Sideshow application in Python
root.mainloop()
#Output : pip install Pillow
[END]
|
Create a Sideshow application in Python
|
https://www.geeksforgeeks.org/create-a-sideshow-application-in-python/
|
# import required modules
import tkinter as tk
from tkinter import *
from PIL import Image
from PIL import ImageTk
# adjust window
root = tk.Tk()
root.geometry("200x200")
# loading the images
img = ImageTk.PhotoImage(Image.open("photo1.png"))
img2 = ImageTk.PhotoImage(Image.open("photo2.png"))
img3 = ImageTk.PhotoImage(Image.open("photo3.png"))
l = Label()
l.pack()
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x + 1
root.after(2000, move)
# calling the function
move()
root.mainloop()
|
#Output : pip install Pillow
|
Create a Sideshow application in Python
# import required modules
import tkinter as tk
from tkinter import *
from PIL import Image
from PIL import ImageTk
# adjust window
root = tk.Tk()
root.geometry("200x200")
# loading the images
img = ImageTk.PhotoImage(Image.open("photo1.png"))
img2 = ImageTk.PhotoImage(Image.open("photo2.png"))
img3 = ImageTk.PhotoImage(Image.open("photo3.png"))
l = Label()
l.pack()
# using recursion to slide to next image
x = 1
# function to change to next image
def move():
global x
if x == 4:
x = 1
if x == 1:
l.config(image=img)
elif x == 2:
l.config(image=img2)
elif x == 3:
l.config(image=img3)
x = x + 1
root.after(2000, move)
# calling the function
move()
root.mainloop()
#Output : pip install Pillow
[END]
|
Visiting Card Scanner GUI Application using Python
|
https://www.geeksforgeeks.org/visiting-card-scanner-gui-application-using-python/
|
# Visiting Card scanner GUI
# imported tkinter library
from tkinter import *
import tkinter.messagebox as tmsg
# Pillow library for importing images
from PIL import Image, ImageTk
# library for filedialog (For file selection)
from tkinter import filedialog
# Pytesseract module importing
import pytesseract
import os.path
root = Tk()
# fixing geometry of GUI
root.geometry("800x500")
root.maxsize(1000, 500)
root.minsize(600, 500)
root.title("Visiting card scanner")
# function for uploading file to GUI
def upload_file():
global filename
global start, last
filename = filedialog.askopenfilename(
initialdir="/Desktop",
title="Select a card image",
filetypes=(("jpeg files", "*.jpg"), ("png files", "*.png")),
)
if filename == "":
t.delete(1.0, END)
t.insert(1.0, "You have not provided any image to convert")
tmsg.showwarning(
title="Alert!", message="Please provide proper formatted image"
)
return
else:
p_label_var.set("Image uploaded successfully")
l.config(fg="#0CDD19")
if (
filename.endswith(".JPG")
or filename.endswith(".JPEG")
or filename.endswith(".jpg")
or filename.endswith(".jpeg")
or filename.endswith(".PNG")
or filename.endswith(".png")
):
filename_rev = filename[::-1]
last = filename.index(".")
start = len(filename) - filename_rev.index("/") - 1
# function for conversion
def convert():
try:
c_label_var.set("Output...")
pytesseract.pytesseract.tesseract_cmd = (
r"C:\Program Files (x86)\Tesseract-OCR\tesseract"
)
text = pytesseract.image_to_string(filename)
t.delete(1.0, END)
t.insert(1.0, text)
root1 = Toplevel()
root1.title("Uploaded image")
img1 = ImageTk.PhotoImage(Image.open(filename))
Label(root1, image=img1).pack()
root1.mainloop()
except:
t.delete(1.0, END)
t.insert(1.0, "You have not provided any image to convert")
tmsg.showwarning(
title="Alert!", message="Please provide proper formatted image"
)
return
f_name = filename[start + 1 : last] + ".txt"
f_name = os.path.join(r"Database", f_name)
f = open(f_name, "w")
f.write(text)
f.close()
# Menu bar and navigation tab creation
mainmenu = Menu(root)
mainmenu.config(font=("Times", 29))
m1 = Menu(mainmenu, tearoff=0)
m1.add_command(
label="Scan/Upload Visiting or Business cards and get all the text of cards",
font=("Times", 13),
)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="Aim", menu=m1)
m2 = Menu(mainmenu, tearoff=0)
m2.add_command(
label="|| Electronics and Communication engineering student ||", font=("Times", 13)
)
m2.add_command(label="|| Coding Enthusiast ||", font=("Times", 13))
root.config(menu=mainmenu)
mainmenu.add_cascade(label="About us", menu=m2)
m3 = Menu(mainmenu, tearoff=0)
m3.add_command(label="E-mail: [email protected]", font=("Times", 13))
m3.add_separator()
m3.add_command(label="Mobile: +91-9587823004", font=("Times", 13))
m3.add_separator()
m3.add_command(
label="LinkedIn: https://www.linkedin.com/in/kartik-mathur-97a825160",
font=("Times", 13),
)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="Contact us", menu=m3)
Label(
text="Visiting card scanner", bg="#FAD2B8", fg="#39322D", font=("Times", 18)
).pack(fill="x")
Label(
text="Python GUI",
bg="#FAD2B8",
fg="#39322D",
font=("Times New Roman", 12, "italic"),
).pack(fill="x")
f1 = Frame()
f1.config(bg="white")
Label(f1, text="Browse photo to upload", width=20, font=("Times", 15), bg="white").pack(
side="left"
)
Label(f1, text="format: png/jpeg", bg="white", width=30).pack(side="right", padx=5)
Button(
f1,
text="Upload card",
bg="#F58D4B",
font=("Times", 15),
width=70,
command=upload_file,
).pack(side="right")
f1.pack(pady=10, fill="x")
p_label_var = StringVar()
p_label_var.set("Please upload an image to scan")
l = Label(textvariable=p_label_var, fg="red", bg="white")
l.pack()
Label(text="??copyright 2020", bg="#433E3B", fg="white", font=("Times", 10)).pack(
side="bottom", fill="x"
)
Label(
text="Developer: Kartik Mathur",
bg="#433E3B",
fg="white",
font=("Times", 10, " italic"),
).pack(side="bottom", fill="x")
t = Text(root, height="9", font=("Times", 13))
t.pack(side="bottom", fill="x")
t.insert(1.0, "Text of converted card will be shown here...", END)
c_label_var = StringVar()
c_label_var.set("Ready for conversion")
c_label = Label(textvariable=c_label_var)
c_label.pack(side="bottom", anchor="w")
Button(
root,
text="Scan and Convert",
bg="#F58D4B",
font=("Times", 15),
width=70,
command=convert,
).pack(pady="10", side="bottom")
root.mainloop()
|
#Output : pip install pytesseract
|
Visiting Card Scanner GUI Application using Python
# Visiting Card scanner GUI
# imported tkinter library
from tkinter import *
import tkinter.messagebox as tmsg
# Pillow library for importing images
from PIL import Image, ImageTk
# library for filedialog (For file selection)
from tkinter import filedialog
# Pytesseract module importing
import pytesseract
import os.path
root = Tk()
# fixing geometry of GUI
root.geometry("800x500")
root.maxsize(1000, 500)
root.minsize(600, 500)
root.title("Visiting card scanner")
# function for uploading file to GUI
def upload_file():
global filename
global start, last
filename = filedialog.askopenfilename(
initialdir="/Desktop",
title="Select a card image",
filetypes=(("jpeg files", "*.jpg"), ("png files", "*.png")),
)
if filename == "":
t.delete(1.0, END)
t.insert(1.0, "You have not provided any image to convert")
tmsg.showwarning(
title="Alert!", message="Please provide proper formatted image"
)
return
else:
p_label_var.set("Image uploaded successfully")
l.config(fg="#0CDD19")
if (
filename.endswith(".JPG")
or filename.endswith(".JPEG")
or filename.endswith(".jpg")
or filename.endswith(".jpeg")
or filename.endswith(".PNG")
or filename.endswith(".png")
):
filename_rev = filename[::-1]
last = filename.index(".")
start = len(filename) - filename_rev.index("/") - 1
# function for conversion
def convert():
try:
c_label_var.set("Output...")
pytesseract.pytesseract.tesseract_cmd = (
r"C:\Program Files (x86)\Tesseract-OCR\tesseract"
)
text = pytesseract.image_to_string(filename)
t.delete(1.0, END)
t.insert(1.0, text)
root1 = Toplevel()
root1.title("Uploaded image")
img1 = ImageTk.PhotoImage(Image.open(filename))
Label(root1, image=img1).pack()
root1.mainloop()
except:
t.delete(1.0, END)
t.insert(1.0, "You have not provided any image to convert")
tmsg.showwarning(
title="Alert!", message="Please provide proper formatted image"
)
return
f_name = filename[start + 1 : last] + ".txt"
f_name = os.path.join(r"Database", f_name)
f = open(f_name, "w")
f.write(text)
f.close()
# Menu bar and navigation tab creation
mainmenu = Menu(root)
mainmenu.config(font=("Times", 29))
m1 = Menu(mainmenu, tearoff=0)
m1.add_command(
label="Scan/Upload Visiting or Business cards and get all the text of cards",
font=("Times", 13),
)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="Aim", menu=m1)
m2 = Menu(mainmenu, tearoff=0)
m2.add_command(
label="|| Electronics and Communication engineering student ||", font=("Times", 13)
)
m2.add_command(label="|| Coding Enthusiast ||", font=("Times", 13))
root.config(menu=mainmenu)
mainmenu.add_cascade(label="About us", menu=m2)
m3 = Menu(mainmenu, tearoff=0)
m3.add_command(label="E-mail: [email protected]", font=("Times", 13))
m3.add_separator()
m3.add_command(label="Mobile: +91-9587823004", font=("Times", 13))
m3.add_separator()
m3.add_command(
label="LinkedIn: https://www.linkedin.com/in/kartik-mathur-97a825160",
font=("Times", 13),
)
root.config(menu=mainmenu)
mainmenu.add_cascade(label="Contact us", menu=m3)
Label(
text="Visiting card scanner", bg="#FAD2B8", fg="#39322D", font=("Times", 18)
).pack(fill="x")
Label(
text="Python GUI",
bg="#FAD2B8",
fg="#39322D",
font=("Times New Roman", 12, "italic"),
).pack(fill="x")
f1 = Frame()
f1.config(bg="white")
Label(f1, text="Browse photo to upload", width=20, font=("Times", 15), bg="white").pack(
side="left"
)
Label(f1, text="format: png/jpeg", bg="white", width=30).pack(side="right", padx=5)
Button(
f1,
text="Upload card",
bg="#F58D4B",
font=("Times", 15),
width=70,
command=upload_file,
).pack(side="right")
f1.pack(pady=10, fill="x")
p_label_var = StringVar()
p_label_var.set("Please upload an image to scan")
l = Label(textvariable=p_label_var, fg="red", bg="white")
l.pack()
Label(text="??copyright 2020", bg="#433E3B", fg="white", font=("Times", 10)).pack(
side="bottom", fill="x"
)
Label(
text="Developer: Kartik Mathur",
bg="#433E3B",
fg="white",
font=("Times", 10, " italic"),
).pack(side="bottom", fill="x")
t = Text(root, height="9", font=("Times", 13))
t.pack(side="bottom", fill="x")
t.insert(1.0, "Text of converted card will be shown here...", END)
c_label_var = StringVar()
c_label_var.set("Ready for conversion")
c_label = Label(textvariable=c_label_var)
c_label.pack(side="bottom", anchor="w")
Button(
root,
text="Scan and Convert",
bg="#F58D4B",
font=("Times", 15),
width=70,
command=convert,
).pack(pady="10", side="bottom")
root.mainloop()
#Output : pip install pytesseract
[END]
|
Create digital clock using Python-Turtle
|
https://www.geeksforgeeks.org/create-digital-clock-using-python-turtle/
|
import time
import datetime as dt
import turtle
# create a turtle to display time
t = turtle.Turtle()
# create a turtle to create rectangle box
t1 = turtle.Turtle()
# create screen
s = turtle.Screen()
# set background color of the screen
s.bgcolor("green")
# obtain current hour, minute and second
# from the system
sec = dt.datetime.now().second
min = dt.datetime.now().minute
hr = dt.datetime.now().hour
t1.pensize(3)
t1.color("black")
t1.penup()
# set the position of turtle
t1.goto(-20, 0)
t1.pendown()
# create rectangular box
for i in range(2):
t1.forward(200)
t1.left(90)
t1.forward(70)
t1.left(90)
# hide the turtle
t1.hideturtle()
while True:
t.hideturtle()
t.clear()
# display the time
t.write(
str(hr).zfill(2) + ":" + str(min).zfill(2) + ":" + str(sec).zfill(2),
font=("Arial Narrow", 35, "bold"),
)
time.sleep(1)
sec += 1
if sec == 60:
sec = 0
min += 1
if min == 60:
min = 0
hr += 1
if hr == 13:
hr = 1
|
#Output : pip install turtle
|
Create digital clock using Python-Turtle
import time
import datetime as dt
import turtle
# create a turtle to display time
t = turtle.Turtle()
# create a turtle to create rectangle box
t1 = turtle.Turtle()
# create screen
s = turtle.Screen()
# set background color of the screen
s.bgcolor("green")
# obtain current hour, minute and second
# from the system
sec = dt.datetime.now().second
min = dt.datetime.now().minute
hr = dt.datetime.now().hour
t1.pensize(3)
t1.color("black")
t1.penup()
# set the position of turtle
t1.goto(-20, 0)
t1.pendown()
# create rectangular box
for i in range(2):
t1.forward(200)
t1.left(90)
t1.forward(70)
t1.left(90)
# hide the turtle
t1.hideturtle()
while True:
t.hideturtle()
t.clear()
# display the time
t.write(
str(hr).zfill(2) + ":" + str(min).zfill(2) + ":" + str(sec).zfill(2),
font=("Arial Narrow", 35, "bold"),
)
time.sleep(1)
sec += 1
if sec == 60:
sec = 0
min += 1
if min == 60:
min = 0
hr += 1
if hr == 13:
hr = 1
#Output : pip install turtle
[END]
|
Draw a Tic Tac Toe Board using Python-Turtle
|
https://www.geeksforgeeks.org/draw-a-tic-tac-toe-board-using-python-turtle/
|
import turtle
# getting a Screen to work on
ws = turtle.Screen()
# Defining Turtle instance
t = turtle.Turtle()
# setting up turtle color to green
t.color("Green")
# Setting Up width to 2
t.width("2")
# Setting up speed to 2
t.speed(2)
# Loop for making outside square of
# length 300
for i in range(4):
t.forward(300)
t.left(90)
# code for inner lines of the square
t.penup()
t.goto(0, 100)
t.pendown()
t.forward(300)
t.penup()
t.goto(0, 200)
t.pendown()
t.forward(300)
t.penup()
t.goto(100, 0)
t.pendown()
t.left(90)
t.forward(300)
t.penup()
t.goto(200, 0)
t.pendown()
t.forward(300)
|
#Output : import turtle
|
Draw a Tic Tac Toe Board using Python-Turtle
import turtle
# getting a Screen to work on
ws = turtle.Screen()
# Defining Turtle instance
t = turtle.Turtle()
# setting up turtle color to green
t.color("Green")
# Setting Up width to 2
t.width("2")
# Setting up speed to 2
t.speed(2)
# Loop for making outside square of
# length 300
for i in range(4):
t.forward(300)
t.left(90)
# code for inner lines of the square
t.penup()
t.goto(0, 100)
t.pendown()
t.forward(300)
t.penup()
t.goto(0, 200)
t.pendown()
t.forward(300)
t.penup()
t.goto(100, 0)
t.pendown()
t.left(90)
t.forward(300)
t.penup()
t.goto(200, 0)
t.pendown()
t.forward(300)
#Output : import turtle
[END]
|
How to make Indian Flag using Turtle -
|
https://www.geeksforgeeks.org/how-to-make-indian-flag-using-turtle-python/
|
import turtle
from turtle import *
# screen for output
screen = turtle.Screen()
# Defining a turtle Instance
t = turtle.Turtle()
speed(0)
# initially penup()
t.penup()
t.goto(-400, 250)
t.pendown()
# Orange Rectangle
# white rectangle
t.color("orange")
t.begin_fill()
t.forward(800)
t.right(90)
t.forward(167)
t.right(90)
t.forward(800)
t.end_fill()
t.left(90)
t.forward(167)
# Green Rectangle
t.color("green")
t.begin_fill()
t.forward(167)
t.left(90)
t.forward(800)
t.left(90)
t.forward(167)
t.end_fill()
# Big Blue Circle
t.penup()
t.goto(70, 0)
t.pendown()
t.color("navy")
t.begin_fill()
t.circle(70)
t.end_fill()
# Big White Circle
t.penup()
t.goto(60, 0)
t.pendown()
t.color("white")
t.begin_fill()
t.circle(60)
t.end_fill()
# Mini Blue Circles
t.penup()
t.goto(-57, -8)
t.pendown()
t.color("navy")
for i in range(24):
t.begin_fill()
t.circle(3)
t.end_fill()
t.penup()
t.forward(15)
t.right(15)
t.pendown()
# Small Blue Circle
t.penup()
t.goto(20, 0)
t.pendown()
t.begin_fill()
t.circle(20)
t.end_fill()
# Spokes
t.penup()
t.goto(0, 0)
t.pendown()
t.pensize(2)
for i in range(24):
t.forward(60)
t.backward(60)
t.left(15)
# to hold the
# output window
turtle.done()
|
#Output : import turtle
|
How to make Indian Flag using Turtle -
import turtle
from turtle import *
# screen for output
screen = turtle.Screen()
# Defining a turtle Instance
t = turtle.Turtle()
speed(0)
# initially penup()
t.penup()
t.goto(-400, 250)
t.pendown()
# Orange Rectangle
# white rectangle
t.color("orange")
t.begin_fill()
t.forward(800)
t.right(90)
t.forward(167)
t.right(90)
t.forward(800)
t.end_fill()
t.left(90)
t.forward(167)
# Green Rectangle
t.color("green")
t.begin_fill()
t.forward(167)
t.left(90)
t.forward(800)
t.left(90)
t.forward(167)
t.end_fill()
# Big Blue Circle
t.penup()
t.goto(70, 0)
t.pendown()
t.color("navy")
t.begin_fill()
t.circle(70)
t.end_fill()
# Big White Circle
t.penup()
t.goto(60, 0)
t.pendown()
t.color("white")
t.begin_fill()
t.circle(60)
t.end_fill()
# Mini Blue Circles
t.penup()
t.goto(-57, -8)
t.pendown()
t.color("navy")
for i in range(24):
t.begin_fill()
t.circle(3)
t.end_fill()
t.penup()
t.forward(15)
t.right(15)
t.pendown()
# Small Blue Circle
t.penup()
t.goto(20, 0)
t.pendown()
t.begin_fill()
t.circle(20)
t.end_fill()
# Spokes
t.penup()
t.goto(0, 0)
t.pendown()
t.pensize(2)
for i in range(24):
t.forward(60)
t.backward(60)
t.left(15)
# to hold the
# output window
turtle.done()
#Output : import turtle
[END]
|
Displaying the coordinates of the points clicked on the image using Python-OpenCV
|
https://www.geeksforgeeks.org/displaying-the-coordinates-of-the-points-clicked-on-the-image-using-python-opencv/
|
# importing the module
import cv2
# function to display the coordinates of
# of the points clicked on the image
def click_event(event, x, y, flags, params):
# checking for left mouse clicks
if event == cv2.EVENT_LBUTTONDOWN:
# displaying the coordinates
# on the Shell
print(x, " ", y)
# displaying the coordinates
# on the image window
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, str(x) + "," + str(y), (x, y), font, 1, (255, 0, 0), 2)
cv2.imshow("image", img)
# checking for right mouse clicks
if event == cv2.EVENT_RBUTTONDOWN:
# displaying the coordinates
# on the Shell
print(x, " ", y)
# displaying the coordinates
# on the image window
font = cv2.FONT_HERSHEY_SIMPLEX
b = img[y, x, 0]
g = img[y, x, 1]
r = img[y, x, 2]
cv2.putText(
img, str(b) + "," + str(g) + "," + str(r), (x, y), font, 1, (255, 255, 0), 2
)
cv2.imshow("image", img)
# driver function
if __name__ == "__main__":
# reading the image
img = cv2.imread("lena.jpg", 1)
# displaying the image
cv2.imshow("image", img)
# setting mouse handler for the image
# and calling the click_event() function
cv2.setMouseCallback("image", click_event)
# wait for a key to be pressed to exit
cv2.waitKey(0)
# close the window
cv2.destroyAllWindows()
|
#Output : import cv2
|
Displaying the coordinates of the points clicked on the image using Python-OpenCV
# importing the module
import cv2
# function to display the coordinates of
# of the points clicked on the image
def click_event(event, x, y, flags, params):
# checking for left mouse clicks
if event == cv2.EVENT_LBUTTONDOWN:
# displaying the coordinates
# on the Shell
print(x, " ", y)
# displaying the coordinates
# on the image window
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, str(x) + "," + str(y), (x, y), font, 1, (255, 0, 0), 2)
cv2.imshow("image", img)
# checking for right mouse clicks
if event == cv2.EVENT_RBUTTONDOWN:
# displaying the coordinates
# on the Shell
print(x, " ", y)
# displaying the coordinates
# on the image window
font = cv2.FONT_HERSHEY_SIMPLEX
b = img[y, x, 0]
g = img[y, x, 1]
r = img[y, x, 2]
cv2.putText(
img, str(b) + "," + str(g) + "," + str(r), (x, y), font, 1, (255, 255, 0), 2
)
cv2.imshow("image", img)
# driver function
if __name__ == "__main__":
# reading the image
img = cv2.imread("lena.jpg", 1)
# displaying the image
cv2.imshow("image", img)
# setting mouse handler for the image
# and calling the click_event() function
cv2.setMouseCallback("image", click_event)
# wait for a key to be pressed to exit
cv2.waitKey(0)
# close the window
cv2.destroyAllWindows()
#Output : import cv2
[END]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.