web自動化之selenium(一)環境搭建


自動化搭建環境

1.自動搭建(一)

#安裝
pip install webdriver-helper

1.1示例

from webdriver_helper import *

#get_webdriver()后,不使用with也會自動關閉瀏覽器
#with get_webdriver() as driver:
#    driver.get("https://www.baidu.com")

#使用get_webdriver會在程序執行完之后自動關閉瀏覽器
driver = get_webdriver()
driver.get("https://www.baidu.com")

2.自動搭建(二)

1.下載第三方庫webdriver_manager

from selenium import webdriver
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager

browser = webdriver.Chrome(ChromeDriverManager().install()) # 會自動匹配瀏覽器版本進行下載對應的驅動
browser.get("https://www.baidu.com")
browser.find_element(By.Id,"kw").send_keys("python")
browser.find_element(By.Id,"su").click()
browser.quit()  # 關閉瀏覽器並退出驅動

執行install()時就會查找Chorme的版本並進行下載,如下圖(目前只支持Chorme瀏覽器)

3.手動搭建

1.下載驅動后,將驅動放置在python.exe目錄(python安裝的根目錄)

火狐:https://github.com/mozilla/geckodriver/releases
谷歌:https://sites.google.com/a/chromium.org/chromedriver/downloads(需FQ)
      http://chromedriver.storage.googleapis.com/index.html
Edge:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

2.下載安裝selenium

pip install selenium -i https://pypi.tuna.tsinghua.edu.cn/simple 

3.使用

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

#使用with時,程序運行結束后,會自動關閉瀏覽器
#with webdrivere.Edge() as driver:
    #driver.get("https://www.baidu.com")
    #driver.find_element(By.ID,"kw").send_keys("python")
    #driver.find_element(By.ID,"su").click()
    #time.sleep(3) # 程序等待3s

#要自己手動或調用代碼關閉瀏覽器
driver= webdriver.Edge()
driver.get("https://www.baidu.com")
driver.find_element(By.ID,"kw").send_keys("python")
driver.find_element(By.ID,"su").click()
time.sleep(3)
driver.close()#關閉瀏覽器


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM