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.ItemNotFoundErrorValueError

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 に答える