Python中的自定义For循环



是否有任何Python方法可以与下面的代码做同样的事情,但要以Python的方式?

我创建了这个代码来抓取网站,但我认为应该有一种更好的方法来将内容添加到列表中,而不是为每个元素重复相同的代码。

以下是我将添加元素的列表:

Proporcao_de_Sobras = []
liq_dir =[]
liq_sobras=[]
liq_reservas=[]
Encerramento=[]
n_emissao =[]
tp_ofert =[]
inv_minimo =[]

这是我用来将元素添加到列表中的代码。

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

这种情况会持续5到6次以上。

下面是另一种使用字典的Python方法:

def get_data(your_lists):
data = {}
for list_index, list_name in enumerate(your_lists):
try:
data[list_name] = [x for x in find_elements_by_xpath(f'//*[@id="tablepress-6"]/tbody/tr[*]/td/span[{(list_index + 1) * 2}]')]
except:
pass
return data
your_lists = ['Proporcao_de_Sobras', 'liq_dir', 'loq_reservas', 'Encerramento', 'n_emissao', 'tp_ofert', 'inv_minimo']
all_data = get_data(your_lists)

Python方式N1,使用列表的可变性:

def get_text(x_path, dest_list):
for x in driver.find_elements_by_xpath(x_path):
dest_list.append(x.text)
Proporcao_de_Sobras = []
get_text('//*[@id="tablepress-6"]/tbody/tr[*]/td/span[2]', Proporcao_de_Sobras)

Python方式N2,使用dicts:

paths = {
'//*[@id="tablepress-6"]/tbody/tr[*]/td/span[2]': [],
'//*[@id="tablepress-6"]/tbody/tr[*]/td/span[4]': [],
....
}
for k, v in paths.items():
for x in driver.find_elements_by_xpath(k):
v.append(x.text)

你可以为它使用一个函数。不过我建议捕捉特定的异常。

def fill_elem(fill_list, xpath):
try:
for x in driver.find_elements_by_xpath(xpath)
fill_list.append(x.text)
except SomeException:
pass
else:
return fill_list
proporcao_de_sobras = []
proporcao_de_sobras = fill_elem(proporcao_de_sobras, r'//*[@id="tablepress-6"]/tbody/tr[*]/td/span[2]')

最新更新