咱們在用Selenium寫自動化程序時候,並不但願程序在實際運行過程當中一直彈Chrome窗口,這個時候就須要讓Chrome默默打開,自動讀取數據,而後默默關閉掉就好。web
#讓chrome用無界面形式打開 chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') driver_chrome = webdriver.Chrome(chrome_options=chrome_options)
代碼:chrome
from selenium import webdriver url = 'https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=driver_chrome.close()%20driver_chrome.quit()&oq=%25E5%2586%2599%25E6%258A%2580%25E6%259C%25AF%25E6%2596%2587%25E7%25AB%25A0%25E5%258E%25BB%25E5%2593%25AA%25E9%2587%258C%25E5%25A5%25BD&rsv_pq=b7b407270017fc3f&rsv_t=b631%2B%2Fcdu8anq1OMvmgCcdPCnsCNNe%2BKKawHK4cgDCDH11XkD1wTbuFFLNc&rqlang=cn&rsv_enter=1&inputT=12858&rsv_n=2&rsv_sug3=40&bs=%E5%86%99%E6%8A%80%E6%9C%AF%E6%96%87%E7%AB%A0%E5%8E%BB%E5%93%AA%E9%87%8C%E5%A5%BD' #讓chrome用無界面形式打開 chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') driver_chrome = webdriver.Chrome(chrome_options=chrome_options) driver_chrome.get(url) #獲取text值 text_value = driver_chrome.find_element_by_xpath('''//*[@id="1"]/h3/a''').text print('text: ' + text_value) #獲取get_attribute值 get_attribute_value = driver_chrome.find_element_by_xpath('''//*[@id="su"]''').get_attribute('value') print('get_attribute: ' + get_attribute_value) #獲取get_property值 get_property_value = driver_chrome.find_element_by_xpath('''//*[@id="kw"]''').get_property('value') print('get_property: ' + get_property_value) #關閉web driver driver_chrome.close() driver_chrome.quit()