在Python中使用循环很麻烦



我想要一个活动来抓取网页。数据网的组成部分是route_data

route_data = ["javascript:mostrarFotografiaHemiciclo( '/wc/htdocs/web/img/diputados/peq/215_14.jpg', '/wc/htdocs/web', 'Batet Lamaña, Meritxell (Presidenta del Congreso de los Diputados)', 'Diputada por Barcelona', 'G.P. Socialista' ,'','');",
"javascript:mostrarFotografiaHemiciclo( '/wc/htdocs/web/img/diputados/peq/168_14.jpg', '/wc/htdocs/web', 'Rodríguez Gómez de Celis, Alfonso (Vicepresidente Primero)', 'Diputado por Sevilla', 'G.P. Socialista' ,'','');",]

我用空值创建了一个字典。

dictionary_data = {"Nombre":None, "Territorio":None, "Partido":None, "url":None}

我必须在dictionary_data中保存每一行:

url = /wc/htdocs/web/img/diputados/peq/215_14.jpg
Nombre = Batet Lamaña, Meritxell
Territorio = Diputada por Barcelona
Partido = G.P. Socialista

因此,和I在route_data上循环。

for i in route_data:
text = i.split(",")
nombre = text[2:4]
territorio = text[4]
partido = text[5]

但输出是:

[" 'Batet Lamaña", " Meritxell (Presidenta del Congreso de los Diputados)'"]  'Diputada por Barcelona'  'G.P. Socialista' 
[" 'Rodríguez Gómez de Celis", " Alfonso (Vicepresidente Primero)'"]  'Diputado por Sevilla'  'G.P. Socialista'

怎样才能在字典里把它纠正过来?

一个简单的解决方案是:

all_routes = []
for i in route_data:
text = re.findall("'.+?'", i)
all_routes.append(
{"Nombre": re.sub('(.*?)', '', text[2]).strip(),
"Territorio": text[3],
"Partido": text[-2],
"Url": text[0]})

最新更新