LoginSignup
genki-mii
@genki-mii

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Python スクレイピングでAttributeError: 'list' object has no attribute 'keys'が発生する

Pythonでスクレイピングツールを作成しています。
URLがIDで管理されているサイトで

作ったコード

import time
from tqdm import tqdm, tqdm_notebook

def scrape_race_results(race_id_list,pre_race_results=[]):
    race_results=pre_race_results
    for race_id in tqdm(race_id_list):
        if race_id in race_results.keys():
            continue
        try:
            url = 'https://db.netkeiba.com/race/'+ race_id
            race_results.append(pd.read_html(url,header=0)[0])
            time.sleep(1)
        except:
            break
    return race_results

for place in range(1,11,1):
    for kai in range(1,6,1):
        for day in range(1,9,1):
            for r in range(1,13,1):
                race_id = '2020'+str(place).zfill(2) + str(kai).zfill(2) + str(day).zfill(2) + str(r).zfill(2)
                race_id_list.append(race_id)

test2 = scrape_race_results(race_id_list,test)

こちらを実行したところ

該当のエラー

AttributeError                            Traceback (most recent call last)
<ipython-input-124-8c899e53e993> in <module>
----> 1 test2 = scrape_race_results(race_id_list,test)

<ipython-input-121-9b788cfd6530> in scrape_race_results(race_id_list, pre_race_results)
      5     race_results=pre_race_results
      6     for race_id in tqdm(race_id_list):
----> 7         if race_id in race_results.keys:
      8             continue
      9         try:

AttributeError: 'list' object has no attribute 'keys'

自分で試したこと

if race_id in race_results.keys():

読み解くと、keysが辞書型なので、エラーが起きているのだと思います。
このif文にリスト型でキーになる文章を入れたいのですが、どうすれば良いのでしょうか?

0

1Answer

AttributeError: 'list' object has no attribute 'keys'

keysが辞書型なので、エラーが起きているではなく、
listオブジェクトがkeyアトリビュートを持っていないと書かれているのですが...

見た感じrace_resultsがそもそもlist型なので以下の感じで書けると思いますよ

if race_id in race_results:
0Like

Comments

  1. @genki-mii

    Questioner
    ありがとうございます!
    この方法で解決しました。

Your answer might help someone💌