Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python BeautifulSoup.findAll函数中捕获异常_Python_Beautifulsoup - Fatal编程技术网

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