Is there any pythonic way to do the same as code bellow, but in a pythonic way?
I created this code for web scraping a website, but I think there should be a better way for adding the contents to lists other than repeating the same code for each element.
here are the lists i will add elements to:
Proporcao_de_Sobras = []
liq_dir =[]
liq_sobras=[]
liq_reservas=[]
Encerramento=[]
n_emissao =[]
tp_ofert =[]
inv_minimo =[]
And here is the code I am using to add the elements to lists.
try:
for x in driver.find_elements_by_xpath('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[2]'):
Proporcao_de_Sobras.append(x.text)
except:
pass
try:
for x in driver.find_elements_by_xpath('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[4]'):
liq_dir.append(x.text)
except:
pass
try:
for x in driver.find_elements_by_xpath('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[6]'):
liq_sobras.append(x.text)
except:
pass
try:
for x in driver.find_elements_by_xpath('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[8]'):
liq_reservas.append(x.text)
except:
pass
try:
for x in driver.find_elements_by_xpath('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[10]'):
Encerramento.append(x.text)
except:
pass
try:
for x in driver.find_elements_by_xpath('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[12]'):
n_emissao.append(x.text)
except:
pass
try:
for x in driver.find_elements_by_xpath('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[14]'):
tp_ofert.append(x.text)
except:
pass
try:
for x in driver.find_elements_by_xpath('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[16]'):
inv_minimo.append(x.text)
except:
pass
This goes on for more 5 or 6 times.
[Proporcao_de_Sobras, liq_dir, ...]and iterate over it. And you can use their index to set yourxvalue inspan[x]. Usingx = index*2 + 2. You can get index usingenumerate()except: passwill bite you at some point and waste much time. Happens to everyone. If you have reasons to believe some exception(s) may be thrown, specify ex:except KeyError, IndexError): pass