我试图通过提取table
中的城市和区号来抓取此afghanistan page。现在,当我试图抓住这个american-samoa page时,findAll()
无法找到<td>
这是真的。如何捕捉这个例外?
这是我的代码:
from bs4 import BeautifulSoup
import urllib2
import re
url = "http://www.howtocallabroad.com/american-samoa"
html_page = urllib2.urlopen(url)
soup = BeautifulSoup(html_page)
areatable = soup.find('table',{'id':'codes'})
d = {}
def chunks(l, n):
return [l[i:i+n] for i in range(0, len(l), n)]
li = dict(chunks([i.text for i in areatable.findAll('td')], 2))
if li != []:
print li
for key in li:
print key, ":", li[key]
else:
print "list is empty"
这是我得到的错误
Traceback (most recent call last):
File "extract_table.py", line 15, in <module>
li = dict(chunks([i.text for i in areatable.findAll('td')], 2))
AttributeError: 'NoneType' object has no attribute 'findAll'
我也试过这个,但也不行。
def gettdtag(tag):
return "empty" if areatable.findAll(tag) is None else tag
all_td = gettdtag('td')
print all_td
答案 0 :(得分:2)
错误表明areatable
为None
:
areatable = soup.find('table',{'id':'codes'})
#areatable = soup.find('table', id='codes') # Also works
if areatable is None:
print 'Something happened'
# Exit out
此外,我使用find_all
代替findAll
和get_text()
代替text
。