我正在尝试遍历一系列表,这些表中的数据并不是在表中统一输入的。我正在使用python&bs4。
这些表中包含立法信息-将它们发送给州长(或不发送),签名(或不给签名),否决(或不给与否)。
我只想返回以下内容:(交货/签字/否决和日期)。或者,(未送达/未签名/未否决且没有日期)。问题是,当我遍历列表时,它遍历每一行并返回每一行的结果。我希望当两种情况都满足时代码停止运行,并且只返回一对结果。见下文:
tablebody=soup.select_one(".table.c-bill--actions-table > tbody")
for item in tablebody.select("td"):
if "delivered to governor" in item.text:
transfer_list.append("delivered to governor")
transfer_list.append(item.find_previous("td").text)
else:
transfer_list.append("not delivered")
transfer_list.append("no date")
tablebody=soup.select_one(".table.c-bill--actions-table > tbody")
for item in tablebody.select("td"):
if "signed" in item.text:
transfer_list.append("signed")
transfer_list.append(item.find_previous("td").text)
else:
transfer_list.append("not signed")
transfer_list.append("no date")
tablebody=soup.select_one(".table.c-bill--actions-table > tbody")
for item in tablebody.select("td"):
if "vetoed" in item.text:
transfer_list.append("vetoed")
transfer_list.append(item.find_previous("td").text)
else:
transfer_list.append("not vetoed")
transfer_list.append("no date")
我目前output
看起来像这样:
['senate Bill S3984',
'Creates the crime of related use of a lethal or explosive device',
'Liz Krueger',
'(D, WF) 28th\xa0Senate District',
'No votes for this bill.',
'A2645',
'not delivered',
'no date',
'not delivered',
'no date',
'not delivered',
'no date',
'not delivered',
'no date',
'not signed',
'no date',
'not signed',
'no date',
'not signed',
'no date',
'not signed',
'no date',
'not vetoed',
'no date',
'not vetoed',
'no date',
'not vetoed',
'no date',
'not vetoed',
'no date'],
有什么想法吗?我只需要(交付,签名,否决)和随附的(日期/无日期)进行一次迭代。
这是因为它正在检查每个<td>
项目。有几种方法可以做到。
只需将所有项目放入列表中,然后查看该项目是否存在。您可以执行的另一种方法是进行其他逻辑检查:
tablebody=soup.select_one(".table.c-bill--actions-table > tbody")
check_list = [item.text.strip() for item in tablebody.select("td")]
if "delivered to governor" in check_list:
transfer_list.append("delivered to governor")
i = check_list.index("delivered to governor")
transfer_list.append(check_list[i+1])
else:
transfer_list.append("not delivered")
transfer_list.append("no date")
if "signed" in check_list:
transfer_list.append("signed")
i = check_list.index("signed")
transfer_list.append(check_list[i+1])
else:
transfer_list.append("not signed")
transfer_list.append("no date")
if "vetoed" in check_list:
transfer_list.append("vetoed")
i = check_list.index("vetoed")
transfer_list.append(check_list[i+1])
else:
transfer_list.append("not vetoed")
transfer_list.append("no date")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句