0

ランダムな Web サイトを取得して要素をカウントする小さなプログラムを作成しようとしています。

これが私のエラーです:

Traceback (most recent call last):
  File "elements counter.py", line 23, in <module>
    if elem[1] == string:
TypeError: 'int' object is unsubscriptable

これが私のコードです:

from urllib2 import Request, urlopen, URLError

print 'Fetching URL..'

try:
    html = urlopen(Request("http://www.randomwebsite.com/cgi-bin/random.pl"))
except URLError:
    html = urlopen(Request("http://www.randomwebsitemachine.com/random_website/"))

print 'Loading HTML..'

ellist = [(None,None),]
isel = False
string = ''

for char in html.read():
    if char == '<':
        isel=True
    elif isel:
        if char == ' ' or char == '>':
            if string in ellist:
                for elem in ellist:
                    if elem[1] == string:
                        elem[0] += 1
            else:
                ellist += (1,string)
            isel = False
            string = ''
        else:
            string += char

print sorted(ellist, key = lambda tempvar: tempvar[0])

html.close()
raw_input()

コードにさらに問題がある場合は指摘してください。

4

1 に答える 1

2

あなたがするとき

            ellist += (1,string)

それは同じです

            ellist.extend((1,string))

のようellistに見えます

[(None, None), 1, string]

forしたがって、ループの 2 番目の要素に到達すると、それはintnot になりtupleます。

代わりに、

            ellist.append((1,string))

または、本当に使用したい場合は+=

            ellist += [(1,string)]

コードの残りの部分は基本的に正しいように見えますが、引用符や HTML コメント内の山かっこを適切に処理できないことに注意してください。HTML を解析したい場合は、Python の HTMLParser モジュール、lxml、または BeautifulSoup など、数多くの HTML パーサーのいずれかを使用してください。

于 2012-04-05T15:52:44.130 に答える