-
Notifications
You must be signed in to change notification settings - Fork 0
/
Web scraping cars with python.py
284 lines (145 loc) · 4.91 KB
/
Web scraping cars with python.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
#!/usr/bin/env python
# coding: utf-8
# # Web Scraping with python--- Jean Carlos Vitola Cabarcas
# link:https://www.cars.com/
# Recuerde ejecutar cada celda en su orden, sino le puedo arrojar error de varibale no definida
#
# ![image.png](attachment:image.png)
#
# ### 1) Importamos los módulos
#
# In[18]:
from bs4 import BeautifulSoup #pip install BeautifulSoup
import requests #pip install requests
import pandas as pd # pip install pandas , # pip install numpy
# ### 2) Petición HTTP GET
# In[19]:
# Dirección la cual queremos escrapear
url="https://www.cars.com/shopping/results/?stock_type=cpo&makes%5B%5D=toyota&models%5B%5D=&list_price_max=&maximum_distance=20&zip="
# ### 2.1 Get Requests
# In[20]:
#objeto response para hacer la petición
response=requests.get(url)
# ### 2.2 Status code
# In[21]:
response.status_code # si la salida es response 200(petición get con exito), 500 Servidor time our, 403 protección de scraper
# ### 3) Objeto Soup
# In[22]:
soup= BeautifulSoup(response.content,"html.parser") #el objeto soup nos permite usar los atributos para sacar las variables de interrres
# In[11]:
soup # contenido de Html como estructura de arból
# ![image.png](attachment:image.png)
#
# ### Results
# In[23]:
#Inspecciono el elemento que quiero parsear como contenedor
results= soup.find_all("div",{"class":"vehicle-card-main"})
results
# In[24]:
object=results[0]
# ### Price
# In[25]:
object.find("span",{"class":"primary-price"}).get_text()
# ### Name
#
# In[26]:
object.find("h2").text
# ### Mileage
# In[27]:
object.find("div",{"class":"mileage"}).text
# ### Rating
# In[28]:
object.find("span",{"class":"sds-rating__count"}).text
# ### Dealer-name
# In[29]:
object.find("div",{"class":"dealer-name"}).text.strip()
# ### Review
# In[30]:
object.find("span",{"class":"sds-rating__link sds-button-link"}).text
# ### Image
# In[31]:
object.find("img")["src"]
# ### Url
# In[32]:
object.find("a")["href"]
# ### For-Loop
# In[33]:
name=[]
mileage=[]
dealer_name=[]
rating=[]
price=[]
img=[]
url=[]
jean="https://www.cars.com/" # identificando el arbol, se observa que el link tiene una parte oculta de dirección
for result in results:
try:
name.append(result.find("h2").get_text())
mileage.append(result.find("div",{"class":"mileage"}).text)
dealer_name.append(result.find("div",{"class":"dealer-name"}).text.strip())
rating.append(result.find("span",{"class":"sds-rating__count"}).text)
price.append(result.find("span",{"class":"primary-price"}).get_text())
img.append(object.find("img")["src"])
url.append(jean + (object.find("a")["href"]))
except:
name.append("n/a")
mileage.append("n/a")
dealer_name("n/a")
rating.append("n/a")
price.append("n/a")
img.append("n/a")
url.append("n/a")
# ### Create DataFrame
# In[34]:
cars_sales=pd.DataFrame({"Name":name,"Mielage":mileage,"dealer_name":dealer_name,"Rating":rating,"Price":price,"Img":img,"Url":url})
# In[35]:
cars_sales
# ### output Excel
#
#
#
#
#
#
# In[36]:
cars_sales.to_excel("cars_sales.xlsx", index=False)
# ### Pagination
# In[37]:
name=[]
mileage=[]
dealer_name=[]
rating=[]
price=[]
img=[]
urlx=[]
for i in range(1,30):
#1) identificar rango de la paginación Variable del sitio
url= 'https://www.cars.com/shopping/results/?page=' + str(i)+'&page_size=20&dealer_id=&keyword=&list_price_max=&list_price_min=&makes[]=toyota&maximum_distance=20&mileage_max=&sort=best_match_desc&stock_type=cpo&year_max=&year_min=&zip='
#Petición HTTP con requests
response=requests.get(url)
# Isntancio el objeto de BS
soup= BeautifulSoup(response.content,"html.parser")
# Busco los contenedores de los elementos a parsear
results= soup.find_all("div",{"class":"vehicle-card-main"})
for result in results:
try:
name.append(result.find("h2").get_text())
mileage.append(result.find("div",{"class":"mileage"}).text)
dealer_name.append(result.find("div",{"class":"dealer-name"}).text.strip())
rating.append(result.find("span",{"class":"sds-rating__count"}).text)
price.append(result.find("span",{"class":"primary-price"}).get_text())
img.append(result.find("img")["src"])
urlx.append((result.find("a")["href"]))
except:
name.append("n/a")
mileage.append("n/a")
dealer_name("n/a")
rating.append("n/a")
price.append("n/a")
img.append("n/a")
urlx.append("n/a")
# In[37]:
jean_vitola=pd.DataFrame({"Name":name,"Mielage":mileage,"dealer_name":dealer_name,"Rating":rating,"Price":price,"Img":img, "Url":urlx})
# In[12]:
jean_vitola
# In[ ]: