利用selenium和Chrome瀏覽器進行自動化網頁搜尋與瀏覽
阿新 • • 發佈:2018-11-21
轉自:https://www.cnblogs.com/liangxuehui/p/5797185.html
功能簡介:利用利用selenium和Chrome瀏覽器,讓其自動開啟百度頁面,並設定為每頁顯示50條,接著在百度的搜尋框中輸入selenium,進行查詢。然後再開啟的頁面中選中“Selenium - 開源中國社群”,並開啟頁面 知識簡介: selenium的作用: 1).最初用於網站自動化測試,近幾年,用於獲取精確的網站快照。 2).可以直接執行在瀏覽器上,讓瀏覽器自動載入頁面,獲取需要的資料,還可以頁面截圖,或者判斷網站上某些動作是否發生。 專案步驟: 1.利用google的Chrome瀏覽器時要安裝chromedriver驅動程式。 下載地址: 下載完後最好和你的python檔案放到一起,以便於後面呼叫。 2.安裝selenium(如果已經安裝請忽略此步驟) windows使用者直接用pip install selenium命令安裝。 3.程式碼展示:from selenium import webdriver from time import sleep # 後面是你的瀏覽器驅動位置,記得前面加r'','r'是防止字元轉義的 driver = webdriver.Chrome(r'C:\Python34\chromedriver_x64.exe') # 用get開啟百度頁面 driver.get("http://www.baidu.com") # 查詢頁面的“設定”選項,並進行點選 driver.find_elements_by_link_text('設定')[0].click() # 開啟設定後找到“搜尋設定”選項,設定為每頁顯示50條 driver.find_elements_by_link_text('搜尋設定')[0].click() sleep(2) m = driver.find_element_by_id('nr') sleep(2) m.find_element_by_xpath('//*[@id="nr"]/option[3]').click() sleep(2) # 處理彈出的警告頁面 driver.find_element_by_class_name("prefpanelgo").click() sleep(2) driver.switch_to_alert().accept() sleep(2) # 找到百度的輸入框,並輸入“selenium” driver.find_element_by_id('kw').send_keys('selenium') sleep(2) # 點選搜尋按鈕 driver.find_element_by_id('su').click() sleep(2) # 在開啟的頁面中找到“Selenium - 開源中國社群”,並開啟這個頁面 driver.find_elements_by_link_text('Selenium - 開源中國社群')[0].click()
4.以下頁面操作都是自動完成