selenium、webdriver打開Chrome瀏覽器閃退問題(版本號一致)

使用selenium、webdriver打開谷歌瀏覽器,登錄頁面後閃退,但是版本號是對應的,是因爲driver的全局變量問題

1、不設置driver爲全局,放在函數內(會閃退)

from selenium import webdriver

# 登陸百度
def main():
    chromedriver_path = r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
    driver = webdriver.Chrome(executable_path=chromedriver_path)
    # 打開頁面
    page = driver.get('https://www.baidu.com/')

if __name__ == "__main__":
    main()

2、把driver放在函數外,爲全局(不會閃退)

from selenium import webdriver

chromedriver_path = r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
driver = webdriver.Chrome(executable_path=chromedriver_path)
# 登陸百度
def main():
    # 打開頁面
    page = driver.get('https://www.baidu.com/')

if __name__ == "__main__":
    main()

3、也可以把driver放在函數內,只要設置爲全局變量就可以

from selenium import webdriver

# 登陸百度
def main():
    global driver
    chromedriver_path = r"C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe"
    driver = webdriver.Chrome(executable_path=chromedriver_path)
    # 打開頁面
    page = driver.get('https://www.baidu.com/')

if __name__ == "__main__":
    main()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章