python 關閉chromedriver 的正確方法 selenium使用webdriver爬取ip地址源碼


driver = webdriver.Chrome()     #初始化driver

 

driver.quit()           #關閉瀏覽器並且退出chromedriver窗口
driver.close()             #關閉瀏覽器但依然存在chromedriver窗口

 

實例代碼:

 1 from selenium import webdriver
 2 from selenium.webdriver.chrome.options import Options
 3 from bs4 import BeautifulSoup
 4 import lxml
 5 
 6 
 7 chrome_options = Options()
 8 chrome_options.add_argument('--headless')   # 無需打開瀏覽器窗口
 9 chrome_options.add_argument('--disable-gpu')
10 
11 chrome_options.add_argument('lang=zh_CN.UTF-8')  # 定義頭部信息
12 chrome_options.add_argument('User-Agent="Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"')
13 
14 driver = webdriver.Chrome(chrome_options=chrome_options)
15 
16 driver.get("https://www.ip138.com/iplookup.asp?ip=114.114.114.114&action=2")
17 html = driver.page_source
18 print(html)
19 
20 #美化html
21 soup = BeautifulSoup(html,'lxml')
22 with open('abcd.html','w',encoding='utf-8') as fd:
23    fd.write(str(soup))
24 
25 #import os
26 #os.system("taskkill /f  chromedriver.exe")
27 #os.system('taskkill /im chromedriver.exe /F')
28 #os.system('taskkill /pid chromedriver.exe /f')
29 
30 #以上操作全部失敗
31 
32 
33 driver.quit()       #關閉瀏覽器並且退出chromedriver
34 #driver.close()     #關閉瀏覽器但內存中依然存在chromedriver

 


免責聲明!

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



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