Python BeautifulSoup.findAll函数中捕获异常
我试图通过提取Python BeautifulSoup.findAll函数中捕获异常,python,beautifulsoup,Python,Beautifulsoup,我试图通过提取表中的城市和区号来解决这个问题。现在,当我尝试刮取这个时,findAll()找不到,这是正确的。如何捕获此异常 这是我的密码: from bs4 import BeautifulSoup
表中的城市和区号来解决这个问题。现在,当我尝试刮取这个时,findAll()
找不到
,这是正确的。如何捕获此异常
这是我的密码:
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'
错误显示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
该死,我几乎写了相同的答案。关于使用某些函数而不是其他函数,请注意:P@Haidro那将是我的下一个任务,了解findAll
与findAll
一步一步地学习python=)@zipc之间的区别,我认为这只是findAll
是BeautifulSoup第3版的一部分,而findAll
是第4版的一部分。但是findAll
在4中仍然有效。看一看
areatable = soup.find('table',{'id':'codes'})
#areatable = soup.find('table', id='codes') # Also works
if areatable is None:
print 'Something happened'
# Exit out