python - 在 BeautifulSoup.findAll 函数中捕获异常

标签 python beautifulsoup

我正在尝试抓取这个 afghanistan page通过提取 table 中的城市和区号.现在,当我尝试抓取这个 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

最佳答案

错误表明 areatableNone:

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 而不是 findAllget_text() 而不是 text

关于python - 在 BeautifulSoup.findAll 函数中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16954693/

相关文章:

Python缩进之谜

Python 和 Beautifulsoup ||写入文件之前使用变量的正则表达式

Python不会写入文件

python-3.x - Beautifulsoup 在标签中获取文本

python - 从网站上抓取表数据

python - Django 和 React 得到 403 禁止

Python 数组分割代码的 Java 代码翻译

python - 如何使用 Google Docs API v1 和 Python 将内嵌图像居中

python - Pandas 和 HDF5 聚合性能

python - 如何使用 beautifulsoup4 从网页中仅提取特定类型的链接