使用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()
非原創,自用記錄