0

我试图绕过这个错误:ItemNotFoundError: insufficient items with name u'No_Thanks'使用 try..except 语句出错。但是,我收到另一个错误消息:NameError: name 'ItemNotFoundError' is not defined. 我不确定为什么会这样。谢谢。这是我正在使用的代码

br = mechanize.Browser()
br.addheaders = [('User-agent', 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1;Trident/5.0)')]
urls = "http://shop.o2.co.uk/mobile_phone/pay_monthly/init/Samsung/Galaxy_Ace_Purple"
r = br.open(urls)
page_child = br.response().read()
soup_child = BeautifulSoup(page_child)
contracts = [tag_c['value']for tag_c in soup_child.findAll('input', {"name": "tariff-duration"})]
data_usage = [tag_c['value']for tag_c in soup_child.findAll('input', {"name": "allowance"})]

for contract in contracts:
    if contract <>"Pay_and_Go":
        for data in data_usage:
            br.select_form('formDuration')
            br.form['tariff-duration']=[contract,]
            try:
                br.form['allowance']=[data,]
            except ItemNotFoundError:
                continue
            br.submit()
            page_child_child = br.response().read()
            soup_child_child = BeautifulSoup(page_child_child)
            items = soup_child_child.findAll('div', {"class": "n-pay-today"})  
4

4 回答 4

2

我猜异常是由mechanize. 尝试:except mechanize.ItemNotFoundError


安装 mechanize 后看来这是正确的:

>>> import mechanize
>>> print mechanize.ItemNotFoundError
<class 'mechanize._form.ItemNotFoundError'>
>>> print mechanize.__version__
(0, 2, 5, None, None)
于 2013-01-23T13:55:22.923 回答
2

如果您在没有 try..except 的情况下运行代码,您可能会得到:

ClientForm.ItemNotFoundError: insufficient items with name u'No_Thanks'

所以错误是在ClientForm模块中定义的。所以你可以抓住它

import ClientForm
....
        try:
            br.form['allowance']=[data,]
        except ClientForm.ItemNotFoundError:
            continue

如果你想捕捉一个更普遍的错误,你也可以用 捕捉它ValueError,因为它ClientForm.ItemNotFoundError是 的子类ValueError

In [10]: import ClientForm
In [15]: ClientForm.ItemNotFoundError.mro()
Out[15]: 
[<class 'ClientForm.ItemNotFoundError'>,
 <class 'ClientForm.LocateError'>,
 <type 'exceptions.ValueError'>,
 <type 'exceptions.StandardError'>,
 <type 'exceptions.Exception'>,
 <type 'exceptions.BaseException'>,
 <type 'object'>]
于 2013-01-23T13:55:46.727 回答
0

您需要导入 ItemNotFoundError 的模块或类定义。这不是标准的 Python 异常,我猜它是 Beautifulsoup 实现中某处定义的异常,但我不确定。

from some.module import ItemNotFoundError
....
except ItemNotFoundError:
    continue
于 2013-01-23T13:56:13.383 回答
0

我需要升级机械化(python-mechanize)

印刷机械化。版本 (0, 2, 5, None, None) 导入工作现在

让我们导入一些稍后需要捕获的异常::

>>> from mechanize import LinkNotFoundError
>>> from mechanize import ItemNotFoundError
于 2014-08-11T11:11:41.877 回答