【问题标题】:Scrapy using loops in PythonScrapy 在 Python 中使用循环
【发布时间】:2021-03-12 19:32:49
【问题描述】:

我想要一个抓取网页的活动。数据网部分为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

因此,我循环了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'

如何在字典中正确输入?

【问题讨论】:

    标签: python string list loops scrapy


    【解决方案1】:

    一个简单的解决方案是:

    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]})
    

    【讨论】:

    • 非常感谢,完美!!
    猜你喜欢
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多