LoginSignup
2
4

More than 3 years have passed since last update.

初心者がSeleniumでWebDriverを使うときにつまづいた時に参考にしたコードなど

Last updated at Posted at 2020-07-29

画面内にない要素をクリックすることはできない

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

スクロールして画面内に出すか、


driver.set_window_size(xxxx,yyyy)

で最初に画面サイズを変更する。
自分は毎回スクロールするのが面倒なので画面サイズを1980、1280にした。
他にもIDなどの要素までスクロールできるっぽい。


ユーザーエージェントがないとロボット扱いしてくるサイトもあるので

options.add_argument(f'user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36')

ユーザーエージェントを偽装する。


Javascriptのボタンなどをクリックできない場合

elements = driver.find_element_by_xpath("XPATH")
loc = elements.location
x, y = loc['x'], loc['y']
actions = ActionChains(driver)
actions.move_by_offset(x, y)
actions.click()
actions.perform()

XPATHの座標でクリックする。


テキストが画面内にないと.textなどでは取得できない

text = driver.find_element_by_id("ID").get_attribute("textContent")

get_attributeで取得する。

おわり

まだ始めて一ヶ月なのでこれ違うよなどツッコミがあるかもしれませんが、優しく言ってくださると幸いです。

2
4
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
2
4