Python:Selenium Chrome無彈窗+property/attribute/text
阿新 • • 發佈:2018-12-17
我們在用Selenium寫自動化程式時候,並不希望程式在實際執行過程中一直彈Chrome視窗,這個時候就需要讓Chrome默默開啟,自動讀取資料,然後默默關閉掉就好。
- 以下是讓chrome用無介面形式開啟方法,主要是chrome_options引數的設定。在使用過程中發現如果chrome瀏覽器版本是v60+的會不起作用,升級到v70+就可以了。
#讓chrome用無介面形式開啟 chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--headless') chrome_options.add_argument('--disable-gpu') driver_chrome = webdriver.Chrome(chrome_options=chrome_options)
- 針對text/get_attribute/get_property這3這的區別:
- text是元素本身的文字內容
- get_attribute是該元素的屬性,或者說是按鈕或者是欄位的title
- get_property是文字框內輸入的內容
程式碼:
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()