抓取此内容时 Afghanistan page ,我收到一条错误消息:
Traceback (most recent call last):
File "extract_table.py", line 23, in <module>
li = dict(chunks([i.text for i in all_td], 2))
ValueError: dictionary update sequence element #28 has length 1; 2 is required
但是在抓取时Argentina page ,代码运行良好。
有什么方法可以判断 all_td
是否返回了新列表?我想知道Python中有哪些函数可以使用。
像这样的伪代码:
if all_td is new list,
execute dict(chunks([i.text for i in all_td], 2))
else
execute dict(chunks([i.text for i in areatable.findAll('td')], 2))
我想要完成的是将代码运行到阿富汗和阿根廷这两个国家。
这是我的代码
from bs4 import BeautifulSoup
import urllib2
import re
url = "http://www.howtocallabroad.com/afghanistan" # argentina works fine
html_page = urllib2.urlopen(url)
soup = BeautifulSoup(html_page)
areatable = soup.find('table',{'id':'codes'})
if areatable is None:
print "areatable is None"
else:
d = {}
def chunks(l, n):
return [l[i : i + n] for i in range(0, len(l), n)]
all_td = areatable.findAll('td')
all_td = filter(lambda x: x.attrs == {}, all_td)
print ">>>>> all_td=", all_td
li = dict(chunks([i.text for i in all_td], 2))
print ">>>>> li=", li
最佳答案
您的过滤器正在消除这 3 个名称,因为 .attrs != {}
<tr>
<td width="25%">Badghis</td>
<td>41</td>
<td width="25%">Kabul</td>
<td>20</td>
<td width="25%">Panjshar</td>
<td>28</td>
</tr>
这就是为什么你会得到一个奇数来分成对。结果就是将数字改造成不相关的名称,即使它最终有一个偶数。
阿根廷工作正常,因为他们没有额外的宽度属性。
这很痛苦,因为现在您知道他们不仅仅是像任何理智的人那样从模板填充这些表。至少有人正在摆弄其中的一些。
在尝试解析这些类型的页面时,您必须更加谨慎地编写代码。
关于python - 如何判断filter()是否返回一个新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16976422/