Repository navigation
Expand file tree
/
Copy pathwebScraping.py
More file actions
144 lines (101 loc) · 3.91 KB
/
Copy pathwebScraping.py
File metadata and controls
144 lines (101 loc) · 3.91 KB
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
import sys
import csv
import json
import time
import mechanize
from bs4 import BeautifulSoup
class webScraping():
def start_scrapig(self):
""" Inicializa Script """
regiao = input("INFORME O ESTADO (EXP.: PI/SP): ").lower()
qtd_pags = int(input("QUANTAS PAGINAS: "))
browser = self.create_browser()
start = time.time()
pag = 1
anuncios = []
while pag <= qtd_pags:
url = f"https://{regiao}.olx.com.br/imoveis?f=p&sf=1&o={pag}"
try:
html = self.request(browser, url)
except:
print("SERVIDOR SOBRECARREGADO...")
continue
links_anuncios = self.get_anuncios(html, regiao)
anuncios += links_anuncios
pag += 1
print("INICIANDO BUSCA DE ANUNCIANTES...")
anunciante = self.get_anunciante(browser, anuncios)
self.save_file(anunciante)
end = time.time()
_time = end - start
print("Finalizado...")
print(f"Tempo...: {_time:.2f}s")
def create_browser(self):
""" Cria e Simula um Browser """
br = mechanize.Browser()
br.set_handle_equiv(True)
br.set_handle_gzip(False)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
br.set_handle_refresh(mechanize._http.HTTPRefreshProcessor(), max_time=1)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11;\
U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615\
Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
return br
def request(self, browser, url):
""" Faz as requisicoes atraves do browser criado """
browser.open(url)
html = browser.response().read()
return html
def get_anuncios(self, html, regiao):
""" Busca os anuncios disponiveis """
soup = BeautifulSoup(html, 'html.parser')
all_ul = soup.find_all('ul')
anuncios = []
for ul in all_ul:
produtos = ul.find_all('li')
for produto in produtos:
if produto.a and str(produto.a).find(f"https://{regiao}.olx.com.br/") >= 0 and str(produto.a).find("?f=p") < 0:
anuncios += [produto.a.get('href')]
return anuncios
def get_anunciante(self, browser, anuncios):
""" Busca as informacoes dos anunciantes """
props = []
for index, anuncio in enumerate(anuncios):
print(f"{index} de {len(anuncios)}...")
try:
html = self.request(browser, anuncio)
except:
print("SERVIDOR SOBRECARREGADO...")
continue
soup = BeautifulSoup(html, 'html.parser')
scripts = soup.find_all('script')
for data in scripts:
if str(data).find('data-json') >= 0:
try:
data = data.attrs
user = json.loads(data['data-json'])['ad']['user']['name']
phone = json.loads(data['data-json'])['ad']['phone']['phone']
if phone:
props += [{'name': user, 'telefone': phone}]
except:
continue
return props
def save_file(self, data):
""" Cria e salva das informacoes em um arquivo CSV """
fieldnames = ['name', 'telefone']
rows = data
with open('anuncios.csv', 'w', encoding='UTF8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
def debugger(self, html):
""" Funcao para analisar erros """
with open("log.txt", "w") as file:
file.write(str(html))
print("FINALIZANDO SISTEMA....")
sys.exit()
if __name__ == '__main__':
web = webScraping()
web.start_scrapig()