Docsity

Python exam - basic notion and how to build a scraper, Appunti di Marketing

Toggle sidebar
bg1
#LECTURE 1
#This is our first programme
#it deals with variable
#let's create a variable
#a variable is an empty box which it store a value
variable=10 #this is a INT variable, meaning INTEGER -> it's an integer number
variable2=10.5 #this is a FLOAT variable -> number with a decimal part
variable3="this is our first program" #this is a STRING -> text variable
#we output data using the PRINT command
print ("our first program")
print (variable)
print (variable2)
print (variable3)
#basic arithmetic operation
variable4=variable+5
variable5=variable2*3
variable6=variable5/4
variable7=(variable+variable2)*variable6+3 #it'a valid the order of operation of
basic math
print (variable4,variable5,variable6,variable7) #print all variables in a row,
no space needed
#how to fit numeric variable in printout of text
print (f"the value of variable7 is: {variable7}") #basta mettere la variabile
all'interno di parentesi graffe, usando Alt Gr + Shift + [ o ]. mettere una f
davanti al codice dentro le parentesi tonde.
#use of formatted print to place a variable inside a text message.
#LECTURE 2
#this is our second script: it deals with power, square roots and
#text manipulation
#variable names must be meaningful for readability of our code
#we has to import the library math to use the square root. if we don't want to
#import the whole library we can import just the SQRT
from math import sqrt
number_to_elevate=10
elevated_number=10**3
print (elevated_number)
#find the square root of a number. firstly import the library at the beginning
of the code
pf3
pf4
pf5
pf8
pf9
pfa
pfd

Anteprima parziale del testo

Scarica Python exam - basic notion and how to build a scraper e più Appunti in PDF di Marketing solo su Docsity!

#LECTURE 1

#This is our first programme #it deals with variable #let's create a variable #a variable is an empty box which it store a value variable=10 #this is a INT variable, meaning INTEGER -> it's an integer number variable2=10.5 #this is a FLOAT variable -> number with a decimal part variable3="this is our first program" #this is a STRING -> text variable #we output data using the PRINT command print ("our first program") print (variable) print (variable2) print (variable3) #basic arithmetic operation variable4=variable+ variable5=variable2* variable6=variable5/ variable7=(variable+variable2)variable6+3 #it'a valid the order of operation of basic math print (variable4,variable5,variable6,variable7) #print all variables in a row, no space needed #how to fit numeric variable in printout of text print (f"the value of variable7 is: {variable7}") #basta mettere la variabile all'interno di parentesi graffe, usando Alt Gr + Shift + [ o ]. mettere una f davanti al codice dentro le parentesi tonde. #use of formatted print to place a variable inside a text message. #LECTURE 2 #this is our second script: it deals with power, square roots and #text manipulation #variable names must be meaningful for readability of our code #we has to import the library math to use the square root. if we don't want to #import the whole library we can import just the SQRT from math import sqrt number_to_elevate= elevated_number=10* print (elevated_number) #find the square root of a number. firstly import the library at the beginning of the code

squared_number=sqrt(100) print (squared_number) #it appears as a FLOAT number print (int(squared_number)) #add INT to transform a float number to an integer number #INT transform a variable to an integer number #FLOAT transform a variable to a floating point number #let's read an input by the user inputed_number=input("please enter a number:") print (inputed_number) #ANYTHING the user input is a string, we need to convert it in a number #AND THEREFORE CANNOT BE USED IN MATH OPERATIONS converted_number=float(inputed_number) #takt the string of the inputed number #and convert it in a floating point number final_number=converted_number* print (f"our final number is: {final_number}") integer_converted_number=int(inputed_number) print (f"our final number is:{integer_converted_number}") #floating numbers are more flexible than integer numbers #NOW LET'S DO TEXT MANIPULATION review="""“Emily in Paris” has a way of driving viewers crazy. There were groans when the Netflix series’ first season was nominated for best comedy at the Golden Globes and at the Emmys. And it occasioned a widely-circulated New Yorker piece that described it as part of a rising trend of “ambient TV,” describing it as “an artifact of contemporary dystopia.” Sure, nominating “Emily in Paris” as on e of the very best shows on TV seems a little overblown. But, as the show’s second season drops Dec. 22, so does describing it as at the forefront of any contemporary movement, much less a dystopian one. Television that exists to be viewed ambiently rather than deeply obsessed over is something that’s been with us throughout the history of the medium; indeed, it’s only relatively recently that televised dramas started being treated as high art. And so it is that in its second season, “Emily in Paris” serves up more of the same, and more of something TV can do well: Charming, watchable, low-friction entertainment in a setting that’s fun to look at. It’s not the best of anything. But it’s good TV. Related Stories An Emmy statue with arrows going through it VIP+ ‘Hacks’ Post-Emmys Boost Highlights Max’s HBO Problem dick pope Dick Pope, Oscar-Nominated Cinematographer of 'Mr. Turner' and 'The Illusionist,' Dies at 77

problem in text cleaning review=review.lower() #convert to lowercase while " " in review: review=review.replace(" "," ") #as long as you finds one go on and clean it. it's circular so it goes on until there are no more double space #what you want to replace with what you want to replace with words=review.split(" ") for word in words: if word=="emily": print ("found") #IT ALWAYS END, NOT FOR WHILE LOOPS IN THIS CASE counter= #while counter #if swamp is written in UPPERCASE this trick doesn't work -> it's not like word, python is very sensitive #we need to transform all the text in lowercase and then apply the replacement replaced_text2=lowered_text.replace("swamp","lake") print (replaced_text2) #CREATE A NEW THONNY PAGE AND CALL IT SILLYLIBRARY #functions: pieces of codes that do something and you can invoke them as if they are commands #to declare a function we use def def greet(name): #create a function called GREET with NAME as input message=f"greetings, {name}" #take name and put it into a string we call "message" return message #give back "message" to the user def average(a,b): #parameters are divided by commas. we create a function called AVERAGE with 2 inputs, a and b result=(a+b)/2 #we create a result variable containing the sum of a + b divided by 2 return result def output_messages(name,age): print(f"{name} is a person of age {age}") def update_dictionary(dictionary,name): age=input(f"please enter the age of {name}:") dictionary[name]=age return dictionary class_dict={"marco":20,"paola":21,"giulio":67,"alessia":19} name='' while name!="quit": name=input("insert a name:") #create a name variable containing the user input if name=="quit": break if name in class_dict.keys(): #check if the name is in the dictionary age=class_dict[name] output_messages(name,age) else: class_dict=update_dictionary(class_dict,name) mygreeting=greet("Chiara and Sara") #create a variable "Mygreeing" invoking the greet function print(mygreeting) #we find the age of the person from our dictionary media=average(10,12) #we feed name and age to our function print(media) #function donm't need to do something but it's just a function #CREATE A NEW THONNY PAGE

clean_text=clean_text.replace(', ',' ') #we replace commas with empty spaces, also here we need to replace commas AND the space after or we will have tons of double spaces clean_text=clean_text.replace('. ',' ') #we replace full stops with empty spaces clean_text=clean_text.replace('; ',' ') #we replace colons with empty spaces clean_text=clean_text.replace(': ',' ') #we replace semicolons with empty spaces #NOW we split the clean text to get a clean list of words clean_words=clean_text.split(" ") print (clean_words) number_of_words=len(clean_words) #this is how we count the number of words in the list. #len returns the number of elements in a list print (f"the total number of words is: {number_of_words}") #LECTURE 5 SCRAPING #build a scraper: #MARIONETTE: the agent that you create to navigate the web #make sure that you have installed google chrome #instrall selenium on tools, then you have to insert manually the webdriver #webdrivermanager takes care of downoloading automatically the necessary driver #IMPORT LIBRARIES from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.keys import Keys # these are the key binding, HOME, PAGE UP AND PAGE DOWN, END from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By #the privacy button mandatory for websites. import By. allows us to specify criteria to find stuff in a web page import pandas as pd import time #TIME LIBRARY is used to perform time-related oepration, including SLEEP

WE CREATE OUR MARIONETTE

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) #LET'S CREATE THE CONTAINER OF OUR RESULTS results=[] # an empty list genres=["Rock","Pop","Jazz"] for genre in genres: for n_page in range (1,11): #driverget sends the marionette somewhere driver.get(f"https://www.discogs.com/it/search/?srsltid=AfmBOooDBE2EJtZ6HthKyYUq MQ-giT-GR272ks7h1a7Q3l3xHjw2rNxo&genre_exact={genre}&page={n_page}")

#to see what lies beneath a web page we have to do "inspect", do it twice to take you exactly there. it'a a tree structure #right click on the specific element, do "copy" and "copy full xpath" time.sleep(2)#sleep for two seconds to give the website time to load #there may not be the cookie button try: accept_button=driver.find_element(By.XPATH,"/html/body/div[2]/div[2]/div/div[1]/ div/div[2]/div/button[1]") accept_button.click() #Now click on the button #li elements are list of items (LI -> list items), they are inside ul element that is a list that contains all the things in the web page #a elements are links clicking on which you will be send to the corrisponding record #span is just text time.sleep(3) except: pass #to make screen scroll ypu need to do two things #find the BODY OF THE PAGE body=driver.find_element(By.CSS_SELECTOR, 'body') #send page_down key to the body for x in range (10): #do the following for 10 times body.send_keys(Keys.PAGE_DOWN) for x in range (2): body.send_keys(Keys.PAGE_UP) #tell him what we are looking for, not xpath, they may change to fool scraper search_results=driver.find_element(By.CSS_SELECTOR,'ul[id="search_results"]') #when yu do CSS SELECTOR, so you find elements not by POSITION like XPATH but by attributes, #ALWAYS ENCLOSE IN SINGLE INVERTED COMMAS #let's find all the LIs inside the UL. plural!!! #THIS PRODUCES A LIST WITH ALL THE FOUND ELEMENTS WITH THE SPECIFIED PARAMETERS records=search_results.find_elements(By.CSS_SELECTOR,'li') for record in records: title_box=record.find_element(By.CSS_SELECTOR, 'div[class="card-release-title"]') title=title_box.find_element(By.CSS_SELECTOR,'A')

#the privacy button mandatory for websites. import By. allows us to specify criteria to find stuff in a web page import pandas as pd import time #TIME LIBRARY is used to perform time-related oepration, including SLEEP

WE CREATE OUR MARIONETT

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) driver.get("https://www.discogs.com") #there meay not be the cookie button try: accept_button=driver.find_element(By.XPATH,"/html/body/div[2]/div[2]/div/div[1]/ div/div[2]/div/button[1]") accept_button.click() #Now click on the button #li elements are list of items (LI -> list items), they are inside ul element that is a list that contains all the things in the web page #a elements are links clicking on which you will be send to the corrisponding record #span is just text time.sleep(3) except: pass artist="Kendrick Lamar" time.sleep(3) search_box=driver.find_element(By.CSS_SELECTOR,'input[placeholder="Ricerca artisti, album e altro..."]') search_box.click() search_box.send_keys(artist) search_box.send_keys(Keys.ENTER) time.sleep(4) results_list=driver.find_element(By.CSS_SELECTOR,'ul[id="search_results"]') results=results_list.find_elements(By.CSS_SELECTOR,'li') #link=results[0].find_element(By.CSS_SELECTOR,'a') #link.click() for result in results: #<-GO THROUGH RESULTS ONE AT AT TIME result_text=result.text #extrat the text in each box if result_text==artist: #IF THE text is equal to what we are looking for link=result.find_element(By.CSS_SELECTOR,'a') #<--find a link in the box link.click()#<<--and click on it input() driver.quit() #LECTURE 6

#MARIONETTE: the agent that you create to navigate the web #make sure that you have installed google chrome #instrall selenium on tools, then you have to insert manually the webdriver #webdrivermanager takes care of downoloading automatically the necessary driver #IMPORT LIBRARIES from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.chrome.service import Service as ChromeService from selenium.webdriver.common.by import By #the privacy button mandatory for websites. import By. allows us to specify criteria to find stuff in a web page import pandas as pd import time #TIME LIBRARY is used to perform time-related oepration, including SLEEP from selenium.webdriver.common.keys import Keys #THIS IS THE LIBRARY THAT CONTAINS KEY BINDINGS -shortcuts to key codes - useful to automate

WE CREATE OUR MARIONETT

driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) #dirver è il ponte che fa parlare la marionetta con il browser urls={ "uomo": {"accessori":"https://it.loropiana.com/it/c/uomo/accessori","scarpe":"https://it .loropiana.com/it/scarpe/uomo","borse":"https://it.loropiana.com/it/c/uomo/leath er-goods"}, "donna": {"accessori":"https://it.loropiana.com/it/c/donna/accessori","scarpe":"https://i t.loropiana.com/it/scarpe/donna","borse":"https://it.loropiana.com/it/c/donna/le ather-goods"} } results=[] #creiamo una lista vuota, conterrà tutti i risultati for genere in urls.keys(): indirizzi=urls[genere] print (genere) for categoria in indirizzi.keys(): print (categoria) indirizzo=indirizzi[categoria] print (indirizzo) driver.get(indirizzo) time.sleep(3) try: cookie_button=driver.find_element(By.XPATH,'/html/body/div[19]/div[2]/div/div/di v[2]/div/div/button') cookie_button.click() time.sleep(2)

#input("PREMI INVIO PER CONTINUARE") driver.quit() driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install())) final_results=pd.DataFrame(results) final_results.to_excel('loropiana_products.xlsx') driver.quit()