LoginSignup
3
2

More than 3 years have passed since last update.

【Python】TypeError: 'WebElement' object is not iterable エラーが発生した時の対処法

Posted at

環境

macOS Catalina 10.15.3
Python 3.6.5
selenium 3.141.0

概要

pythonのseleniumで、Google検索結果のスクレイピングを行い
取り出した要素をforループで更にリストに抽出

発生した課題

'WebElement' object is not iterable
訳:'WebElement'オブジェクトは反復可能ではありません

ここではforループを行った時に発生したエラーでしたので、要は
for i in xxx で参照元として指定している’xxx’は、繰り返し要素を取り出すことができませんよ。ということですね。

サンプルコード

この際、seleniumuを使った前処理は割愛します。

title_list = []
link_list = []
i = 1
i_max = 2

while i <= i_max:
    w = driver.find_element_by_class_name(“x”)
    for elem in x:
         title_list.append(elem.find_element_by_class_name(‘y’).text)           
         link_list.append(elem.find_element_by_tag_name(‘a’).get_attribute('href')) 

上記のコードでエラー発生

TypeError: 'WebElement' object is not iterable

原因

# 7行目のココ
w = driver.find_element_by_class_name(“x”)

.find_element では単一要素しか抽出されませんので、反復不可能というわけですね。

解決法

# .find_elements…にしてください
w = driver.find_elements_by_class_name(“x”)

単一の要素抽出なのか、それとも複数必要なのかということは注意しながら書かなければいけませんね。
勉強になりました。

参照

「PythonでGoogle検索タイトルとURL一覧を抽出してみた」
https://watlab-blog.com/2019/08/15/python-google-searchlist/

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2