Advertisement
lancernik

OtoScrpv9

Apr 27th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.35 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Thu Apr 25 09:06:22 2019
  4.  
  5. @author: lancernik
  6. """
  7.  
  8. # -*- coding: utf-8 -*-
  9. """
  10. Created on Wed Apr 24 23:35:43 2019
  11.  
  12. @author: lancernik
  13. """
  14.  
  15.  
  16. from requests import get
  17. from requests.exceptions import RequestException
  18. from contextlib import closing
  19. from bs4 import BeautifulSoup
  20. import string
  21. import re
  22. from itertools import groupby
  23. import pandas as pd
  24. import time
  25. import matplotlib.pyplot as plt
  26. import numpy as np
  27. from scipy.stats import kde
  28. import seaborn as sns
  29. from sklearn.linear_model import LinearRegression
  30.  
  31.  
  32.  
  33. def simple_get(url):
  34. #Zwraca none, w przypadku problemu z pobraniem danych
  35. try:
  36. with closing(get(url, stream=True)) as resp:
  37. if is_good_response(resp):
  38. return resp.content
  39. else:
  40. return None
  41.  
  42. except RequestException as e:
  43. log_error('Error during requests to {0} : {1}'.format(url, str(e)))
  44. return None
  45.  
  46. def is_good_response(resp):
  47. #Zwaraca True, jeżeli HTMl
  48. content_type = resp.headers['Content-Type'].lower()
  49. return (resp.status_code == 200
  50. and content_type is not None
  51. and content_type.find('html') > -1)
  52.  
  53. def log_error(e):
  54. print(e)
  55.  
  56. def lastpage(page):
  57. lastepage_out=0
  58. lastpage = str(page.find_all(class_="page"))
  59. lastpage_all = [int(s) for s in re.findall(r'\b\d+\b',lastpage)]
  60. lastpage_out = lastpage_all[-1]
  61. return lastepage_out
  62.  
  63. def scrappy(page): #Pobiera dane z konretnej strony
  64.  
  65. datadict = {'Milage':[0],'Age':[0],'Price':[0],'Engine capacity':[0],'Fuel type':[0]}
  66. dataset = pd.DataFrame(data=datadict)
  67.  
  68.  
  69. #Zdobywa numer ostatniej strony
  70.  
  71. lastpage = str(page.find_all(class_="page"))
  72. lastpage_all = [int(s) for s in re.findall(r'\b\d+\b',lastpage)]
  73. lastpage_out = lastpage_all[-1]
  74.  
  75. #Scrapowanie przebiegu
  76.  
  77. milage_from_page = ''.join(map(str,(page.find_all("li", {"data-code" : "mileage"}))))
  78. milage_from_page_nospace = milage_from_page.translate({ord(c): None for c in string.whitespace})
  79. milage_page_out = [int(''.join(i)) for is_digit, i in groupby(milage_from_page_nospace, str.isdigit) if is_digit]
  80.  
  81. #Scrapowanie roku z danej strony
  82.  
  83. age_from_page = str(page.find_all(class_="offer-item__params-item"))
  84. age_from_page_nospace = age_from_page.translate({ord(c): None for c in string.whitespace})
  85. age_from_page_out = [int(s) for s in re.findall(r'\b\d+\b',age_from_page_nospace)]
  86.  
  87. # Scrapowanie cen z danej strony
  88.  
  89. price_from_page = str(page.find_all(class_="offer-price__number"))
  90. price_from_page_nospace = price_from_page.translate({ord(c): None for c in string.whitespace})
  91. price_from_page_out = [int(s) for s in re.findall(r'\b\d+\b',price_from_page_nospace)]
  92.  
  93. # Scrapowanie pojemnosci silnika
  94.  
  95. capacity_from_page = ''.join(map(str,(page.find_all("li", {"data-code" : "engine_capacity"}))))
  96. capacity_from_page_nospace = capacity_from_page.translate({ord(c): None for c in string.whitespace})
  97. capacity_page_out1 = [int(''.join(i)) for is_digit, i in groupby(capacity_from_page_nospace, str.isdigit) if is_digit]
  98. capacity_page_out = [cap for cap in capacity_page_out1 if cap !=3]
  99.  
  100. # Scrapowanie rodaju paliwa
  101.  
  102. fueltype_from_page = ''.join(map(str,(page.find_all("li", {"data-code" : "fuel_type"}))))
  103. fueltype_from_page_nospace = fueltype_from_page.translate({ord(c): None for c in string.whitespace})
  104. fueltype_from_page_nospace = fueltype_from_page_nospace.replace("Benzyna","1")
  105. fueltype_from_page_nospace = fueltype_from_page_nospace.replace("Diesel","2")
  106. fueltype_from_page_nospace = fueltype_from_page_nospace.replace("Benzyna+LPG","3")
  107. fueltype_from_page_nospace = fueltype_from_page_nospace.replace("Elektryczny","4")
  108. fueltype_from_page_nospace = fueltype_from_page_nospace.replace("Hybryda","5")
  109. fueltype_from_page_out = [int(s) for s in re.findall(r'\b\d+\b',fueltype_from_page_nospace)]
  110.  
  111. if len(milage_page_out) == len(age_from_page_out) == len(price_from_page_out) == len(capacity_page_out):
  112. df = pd.DataFrame(
  113. {'Milage':milage_page_out,
  114. 'Age': age_from_page_out,
  115. 'Price': price_from_page_out,
  116. 'Engine capacity':capacity_page_out,
  117. 'Fuel type':fueltype_from_page_out})
  118.  
  119. dataset = dataset.append(df,ignore_index=True)
  120.  
  121. return dataset
  122.  
  123.  
  124. def ScrapPage(marka,model,start,stop): #Oczyszcza dane, wyznacza zares stron
  125. datadict = {'Milage':[0],'Age':[0],'Price':[0]}
  126. dataset_out = pd.DataFrame(data=datadict)
  127. for i in range(start,stop): #Docelowo 1, lastpage
  128. time.sleep(2)
  129.  
  130. #To w formacie beda kolejne argumenty, tj za opel i corsa
  131. url = simple_get('https://www.otomoto.pl/osobowe/{}/{}/?search%5Bfilter_float_mileage%3Afrom%5D=0&search%5Bfilter_float_engine_capacity%3Afrom%5D=0&search%5Bbrand_program_id%5D%5B0%5D=&search%5Bcountry%5D=&page={}'.format(marka,model,i))
  132. page = BeautifulSoup(url, 'html.parser')
  133. # print(scrappy(page))
  134. dataset_out = dataset_out.append(scrappy(page), ignore_index=True)
  135. print(dataset_out)
  136. print(i)
  137.  
  138.  
  139. #Usuwanie danych odstających
  140.  
  141. clear = dataset_out.Milage[((dataset_out.Milage - dataset_out.Milage.mean()) / dataset_out.Milage.std()).abs() > 2]
  142. clear = clear.append(dataset_out.Age[((dataset_out.Age - dataset_out.Age.mean()) / dataset_out.Age.std()).abs() > 2])
  143. clear = clear.append(dataset_out.Price[((dataset_out.Price - dataset_out.Price.mean()) / dataset_out.Price.std()).abs() > 3])
  144. test = clear.index.get_values()
  145.  
  146. for i in range(0,len(test)):
  147. dataset_out = dataset_out.drop(test[i],axis=0)
  148.  
  149. return dataset_out
  150.  
  151.  
  152. def ClearCarData():
  153. clear = dataset_out.Milage[((dataset_out.Milage - dataset_out.Milage.mean()) / dataset_out.Milage.std()).abs() > 2]
  154. clear = clear.append(dataset_out.Age[((dataset_out.Age - dataset_out.Age.mean()) / dataset_out.Age.std()).abs() > 2])
  155. clear = clear.append(dataset_out.Price[((dataset_out.Price - dataset_out.Price.mean()) / dataset_out.Price.std()).abs() > 3])
  156. test = clear.index.get_values()
  157.  
  158. for i in range(0,len(test)):
  159. dataset_out = dataset_out.drop(test[i],axis=0)
  160. return dataset_out
  161.  
  162. def LoadCarData(filename):
  163. dataset_out = pd.read_csv('{}.csv'.format(filename)) #9-45
  164. clear = dataset_out.Milage[((dataset_out.Milage - dataset_out.Milage.mean()) / dataset_out.Milage.std()).abs() > 2]
  165. clear = clear.append(dataset_out.Age[((dataset_out.Age - dataset_out.Age.mean()) / dataset_out.Age.std()).abs() > 2])
  166. clear = clear.append(dataset_out.Price[((dataset_out.Price - dataset_out.Price.mean()) / dataset_out.Price.std()).abs() > 3])
  167. test = clear.index.get_values()
  168.  
  169. for i in range(0,len(test)):
  170. dataset_out = dataset_out.drop(test[i],axis=0)
  171. return dataset_out
  172.  
  173. def regress(x,y):
  174. model = LinearRegression()
  175. model.fit(x,y)
  176. model.predict([[100]])
  177.  
  178. x_test = np.linspace(0,400000)
  179. y_pred = model.predict(x_test[:,None])
  180.  
  181. plt.scatter(x,y,s=2)
  182. plt.plot(x_test,y_pred,'r')
  183. plt.legend(['Regresja', 'Kropeczki'])
  184. plt.show()
  185.  
  186. def Plot1(x,y):
  187.  
  188. # Evaluate a gaussian kde on a regular grid of nbins x nbins over data extents
  189. nbins=300
  190. k = kde.gaussian_kde([x,y])
  191. xi, yi = np.mgrid[x.min():x.max():nbins*1j, y.min():y.max():nbins*1j]
  192. zi = k(np.vstack([xi.flatten(), yi.flatten()]))
  193.  
  194. # Make the plot
  195. plt.pcolormesh(xi, yi, zi.reshape(xi.shape))
  196. plt.show()
  197.  
  198. # Change color palette
  199. plt.pcolormesh(xi, yi, zi.reshape(xi.shape), cmap=plt.cm.Greens_r)
  200. plt.show()
  201. def Plot2(x,y):
  202. # Make the plot
  203. plt.hexbin(x, y, gridsize=(15,15) )
  204. plt.show()
  205.  
  206. # We can control the size of the bins:
  207. plt.hexbin(x, y, gridsize=(150,150) )
  208. plt.show()
  209. def Plot3(x,y):
  210. sns.jointplot(x, y, kind='scatter')
  211. sns.jointplot(x, y, kind='hex')
  212. sns.jointplot(x, y, kind='kde')
  213.  
  214. # Then you can pass arguments to each type:
  215. sns.jointplot(x, y, kind='scatter', s=200, color='m', edgecolor="skyblue", linewidth=2)
  216.  
  217. # Custom the color
  218. sns.set(style="white", color_codes=True)
  219. sns.jointplot(x, y, kind='kde', color="skyblue",xlim={-30000,300000})
  220.  
  221.  
  222.  
  223.  
  224.  
  225.  
  226.  
  227. #LoadCarData(filename): Wczytuje dane z pliku CSV stworzonego przez funkcje ScrapPage,
  228. #dodatkowo oczyszcza z danych odstajcych
  229.  
  230. #ClearCarData(): Oczyszcza z danych odstajacych, zdiala tylko dla df o nazwie dataset_out
  231.  
  232.  
  233.  
  234.  
  235. # 1) Scrapuje dane
  236.  
  237. # Marka, model, start, stop
  238. dataset_out = ScrapPage("audi" ,"a3", 1 ,4)
  239. dataset_out.to_csv('dataset1.csv')
  240. #dataset_out = pd.read_csv('datasetgolf.csv') #9-45
  241.  
  242.  
  243. # 2) Wczytuje zeskrapowane dane
  244.  
  245. #dataset_out = LoadCarData("datasetgolf")
  246.  
  247. #Rozne ploty
  248.  
  249. x=dataset_out['Milage']
  250. y=dataset_out['Age']
  251. #
  252. #
  253. #Plot1(x,y)
  254. #Plot2(x,y)
  255. #Plot3(x,y)
  256.  
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263. #Regresja przebiegu względem czasu
  264. #
  265. a=np.array(dataset_out['Milage'].tolist()).reshape(-1,1)
  266. b=np.array(dataset_out['Age'].tolist()).reshape(-1,1)
  267. regress(a,b)
  268.  
  269.  
  270.  
  271.  
  272.  
  273.  
  274. #To sie przyda do wojewodztw
  275. #for i, li in enumerate(page.select('li')): #To się przyda do wojedzowtw
  276. # print(i, li.text)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement