Urllib2 & BeautifulSoup: Bom casal, mas muito lento - urllib3 & threads?
Eu estava olhando para encontrar uma maneira de otimizar meu código quando ouvi algumas coisas boas sobre tópicos e urllib3. Aparentemente, as pessoas discordam qual solução é a melhor.
O problema com o meu script abaixo é o tempo de execução: tão lento!
Passo 1: Eu busco esta páginahttp://www.cambridgeesol.org/institutions/results.php?region=Afghanistan&type=&BULATS=on
Passo 2: Eu analiso a página com BeautifulSoup
Etapa 3: Eu coloquei os dados em um excel doc
Passo 4: Eu faço isso de novo, e de novo, e de novo para todos os países da minha lista (lista grande) (estou mudando apenas "Afeganistão" no URL para outro país)
Aqui está o meu código:
<code>ws = wb.add_sheet("BULATS_IA") #We add a new tab in the excel doc x = 0 # We need x and y for pulling the data into the excel doc y = 0 Countries_List = ['Afghanistan','Albania','Andorra','Argentina','Armenia','Australia','Austria','Azerbaijan','Bahrain','Bangladesh','Belgium','Belize','Bolivia','Bosnia and Herzegovina','Brazil','Brunei Darussalam','Bulgaria','Cameroon','Canada','Central African Republic','Chile','China','Colombia','Costa Rica','Croatia','Cuba','Cyprus','Czech Republic','Denmark','Dominican Republic','Ecuador','Egypt','Eritrea','Estonia','Ethiopia','Faroe Islands','Fiji','Finland','France','French Polynesia','Georgia','Germany','Gibraltar','Greece','Grenada','Hong Kong','Hungary','Iceland','India','Indonesia','Iran','Iraq','Ireland','Israel','Italy','Jamaica','Japan','Jordan','Kazakhstan','Kenya','Kuwait','Latvia','Lebanon','Libya','Liechtenstein','Lithuania','Luxembourg','Macau','Macedonia','Malaysia','Maldives','Malta','Mexico','Monaco','Montenegro','Morocco','Mozambique','Myanmar (Burma)','Nepal','Netherlands','New Caledonia','New Zealand','Nigeria','Norway','Oman','Pakistan','Palestine','Papua New Guinea','Paraguay','Peru','Philippines','Poland','Portugal','Qatar','Romania','Russia','Saudi Arabia','Serbia','Singapore','Slovakia','Slovenia','South Africa','South Korea','Spain','Sri Lanka','Sweden','Switzerland','Syria','Taiwan','Thailand','Trinadad and Tobago','Tunisia','Turkey','Ukraine','United Arab Emirates','United Kingdom','United States','Uruguay','Uzbekistan','Venezuela','Vietnam'] Longueur = len(Countries_List) for Countries in Countries_List: y = 0 htmlSource = urllib.urlopen("http://www.cambridgeesol.org/institutions/results.php?region=%s&type=&BULATS=on" % (Countries)).read() # I am opening the page with the name of the correspondant country in the url s = soup(htmlSource) tableGood = s.findAll('table') try: rows = tableGood[3].findAll('tr') for tr in rows: cols = tr.findAll('td') y = 0 x = x + 1 for td in cols: hum = td.text ws.write(x,y,hum) y = y + 1 wb.save("%s.xls" % name_excel) except (IndexError): pass </code>
Então eu sei que nem tudo é perfeito, mas estou ansioso para aprender coisas novas em Python! O script é muito lento porque o urllib2 não é tão rápido e o BeautifulSoup. Para a coisa da sopa, eu acho que não posso melhorar, mas para o urllib2, eu não faço.
EDIT 1:Multiprocessamento inútil com urllib2? Parece ser interessante no meu caso. O que vocês acham dessa solução potencial ?!
<code># Make sure that the queue is thread-safe!! def producer(self): # Only need one producer, although you could have multiple with fh = open('urllist.txt', 'r'): for line in fh: self.queue.enqueue(line.strip()) def consumer(self): # Fire up N of these babies for some speed while True: url = self.queue.dequeue() dh = urllib2.urlopen(url) with fh = open('/dev/null', 'w'): # gotta put it somewhere fh.write(dh.read()) </code>
EDIT 2: URLLIB3 Alguém pode me dizer mais coisas sobre isso?
Reutilize a mesma conexão de soquete para várias solicitações (HTTPConnectionPool e HTTPSConnectionPool) (com verificação de certificado do lado do cliente opcional).https://github.com/shazow/urllib3
Tanto quanto eu estou pedindo 122 vezes o mesmo site para páginas diferentes, eu acho que reutilizar a mesma conexão de soquete pode ser interessante, estou errado? Não pode ser mais rápido? ...
<code>http = urllib3.PoolManager() r = http.request('GET', 'http://www.bulats.org') for Pages in Pages_List: r = http.request('GET', 'http://www.bulats.org/agents/find-an-agent?field_continent_tid=All&field_country_tid=All&page=%s' % (Pages)) s = soup(r.data) </code>