LoginSignup
genki-mii
@genki-mii

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

【Python】スクレイピングで取得したデータフレームをfor文で連結したい

スクレイピングを行い、取得したいデータフレームをfor文で連結したいと思っています。

①各URLにテーブルがあるので、read_htmlで取得
②付随するデータを取得し、①で取得したデータフレームに連結
③取得したデータフレームをconcatで連結

test.py
test_list=url_list[:2]

for url in tqdm(test_list):
  try:
    driver.get(url)
    html = driver.page_source.encode('utf-8')
    soup = BeautifulSoup(html, "html.parser")

    #差枚数以外のデータを取得
    data=pd.read_html(url)[0]
    data_test=data.drop([1,2,3,4,5,6,7,8,9,10,11,12,13], axis=0)

    #台番の取得
    no_list=[]
    no=soup.find("p",attrs={"class":"unit_no"})

    for i in no:
      no_list.append(i.string)

    data_test["unit_number"]=num_list

    #機種名のリスト
    name_list=[]
    name=soup.find_all("p",attrs={"class":"name"})

    for s in name:
      name_list.append(s.string)

    #機種名をDFに追加する
    data_test["unit_name"]=name_list

    #ホール名取得
    hall=soup.find_all("div",attrs={"class":"store-ttl"})
    hall_name_list=[]

    for u in hall:
      hall_name_list.append(u.string)

    data_test["hall_name"]=hall_name_list

    time.sleep(3)

    for d in len(data_test):
      data_test_all=pd.concat([d], axis=1, join_axes=[d.index])

  except Exception as e:
    print(e)

上記①~③の流れで、取得したデータフレームを連結したいのですが、エラーが出ます。

test.py
'int' object is not iterable

どうやらデータフレームをfor文で連結するときに整数型のオブジェクトがあるから
エラーが出ているのですが、どうすればよいでしょうか?

0

2Answer

pythonのfor文は「他の言語におけるforeach文に相当し、リスト(配列)などのイテラブルオブジェクトの要素が順番に変数に代入され処理が行われ」ます。
(参考:Pythonのfor文によるループ処理(range, enumerate, zipなど) | note.nkmk.me

―― for 文ってなに?
ひとつ、ひとつ、順番に
オブジェクトを
取り出す時に使います。

(参考:Python の for 文ってなに? | 民主主義に乾杯

整数型オブジェクトはイテラブル(1つ以上のオブジェクトを含んだり生成したりするもの)ではないので、エラーが出ます。

In [1]: for i in [1]:
   ...:     print(i)
1

In [2]: for i in 1:
   ...:     print(i)
TypeError: 'int' object is not iterable
0Like

43行目

    for d in len(data_test):
      data_test_all=pd.concat([d], axis=1, join_axes=[d.index])

len は配列などの値の数を返すので整数になりますね。 'int' object is not iterable とエラーが出たのはこの部分だと想像しますので、 len を外せばよいかと思います。

15行目

    no=soup.find("p",attrs={"class":"unit_no"})

    for i in no:
      no_list.append(i.string)

soup.find の返り値は bs4.element.Tag のインスタンスになるかと思います。 bs4.element.Tag も iterable ではありますが、no という変数の名前からして、本来取得しようとしているものと違う気がします。おそらく "unit_no" というクラスの値をリストで取得したいと想像したので、ここでは soup.find ではなく soup.find_all を使ってみてはどうでしょうか

0Like

Your answer might help someone💌