" />
本ページはプロモーションが含まれています。

スポンサーリンク

Selenium

[Selenium]NameError: name 'By' is not definedの対処法

Seleniumのコードを実行したところ、次のエラーが出ました。

% python3 main.py
Traceback (most recent call last):
  File "/Users/noricgeographic/repositories/keyword-crowler/main.py", line 13, in <module>
    element = driver.find_element(By.CLASS_NAME, "ziIQd")
NameError: name 'By' is not defined

Byというモジュールが見つからないというエラーですので、
Byというモジュールを次のようにインポートしてあげると直ります。

import time
import chromedriver_binary #パスを通すのに必要
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys

driver = webdriver.Chrome()
driver.get("https://www.google.com/")

#テキストボックスに武田薬品と入力
element = driver.find_element(By.CLASS_NAME, "textbox")
element.send_keys("武田薬品")

#Enterキーを押下して検索を実行
element.send_keys(Keys.ENTER)

time.sleep(10)
driver.quit()

スポンサーリンク

-Selenium