Selenium モジュール: ブラウザを開いて、人間のようにブラウザを操作できます. プログラマは、Web ページのさまざまな情報を Selenium から直接抽出できます.
環境のインストール
1.pipインストールセレン
2. ブラウザー ドライバーをダウンロードします: https://npm.taobao.org/mirrors/chromedriver
解凍したブラウザードライバー chromedriver を、python インタープリターが配置されているフォルダーに配置します。
Selenium で Google Chrome を起動する
from selenium.webdriver import Chrome
# 1.创建浏览器对象
web = Chrome()
# 2.打开网址
web.get("XXXXX")
セレン構文
1.要素を見つけて、要素をクリックするプロセスをシミュレートします
el = web.find_element_by_xpath("XXXX")
el.click()
2. 入力ボックスにシミュレートし、python と入力してから Enter を入力します。
from selenium.webdriver.common.keys import keys
web.find_element_by_xpath('XXXXX').send_keys("python",Keys.ENTER)
3. データが保存されている場所を見つけてデータを抽出する
li_list = web.find_elements_by_xpath("XXXXX")
for li in li_list:
name = li.find_element_by_tag_name("XXXXX").text
Selenium ウィンドウの切り替え
el = web.find_element_by_xpath("XXXX")
el.click() #产生了新窗口
#在selenium视角中新窗口默认不切换
web.switch_to.window(web.window_handles[-1])
#关掉子窗口
web.close()
web.switch_to.window(web.window_handles[0])
#变更selenium的窗口视角,回到原来窗口中
iframe を処理する
iframe を扱うには、まず iframe を取得してから、視野角を iframe に切り替えてからデータを取得する必要があります。
iframe = web.find_element_by_xpath("XXXXX")
web.switch_to.frame(iframe)
web.switch_to.default_content() #切换回元页面
Selenium ハンドル ドロップダウン リスト
from selenium.webdriver.support.select import Select
#定位到下拉列表
sel_el = web.find_element_by_xpath("XXX")
#对元素进行包装,包装成下拉菜单
sel = Select(sel_el)
#让浏览器进行调整选项
for i in range(len(sel.options)):
sel.select_by_index(i)
ヘッドレス ブラウザ
ヘッドレス ブラウザとは、Selenium を使用して Web ページを自動的にポップアップさせずに操作することを指します。
from selenium.webdriver.chrome.option import Options
opt = Options()
opt.add_argument("--headless")
opt.add_argument("--disable-gpu")
web = Chrome(options=opt)
Selenium イベント チェーン処理画像検証コード
from selenium.webdriver.common.cation_chains import ActionChains
ActionChains(web).move_to_element_with_offset(verify_img_element,x,y).click().perform()