Python+Selenium筆記(一):環境配置+簡單的例子,pythonselenium

來源:互聯網
上載者:User

Python+Selenium筆記(一):環境配置+簡單的例子,pythonselenium

#環境配置基於windows作業系統

#學習selenium要有一些HTML和xpth的基礎,完全不會的建議先花點時間學點基礎(不然元素定位,特別是xpth可能看的有點懵)

#HTML :  http://www.runoob.com/html/     #xpth:  http://www.runoob.com/xpath

(一)  環境配置

(1)執行下面的命令(前提:已經安裝python環境,可以參考之前發的python筆記(一))

pip install -U selenium

(2)http://docs.seleniumhq.org/download/   (網站打不開的話就FQ)

去下載Mozilla GeckoDriver(因為我暫時用Firefox測試,所以下載這個),解壓後放到任意目錄下,然後在系統變數path中加上解壓後的路徑(我在2台電腦上試了下,一個放在任意目錄,一個放到python的安裝目錄,反正都能用。)

(3)之後如果建立瀏覽器驅動執行個體還是報錯的話(可能是瀏覽器版本的問題,我python3.6+selenium3.9+Firefox47+Mozilla GeckoDriverV0.19.1就報錯,Firefox換成58就不會了)

(二)  簡單的例子

#匯入webdriver
from selenium import webdriver
#FirefoxBinary--匯入2進位檔案所在的位置
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
#指定Firefox瀏覽器的二進位路徑
firefox = FirefoxBinary(r"C:\Program Files (x86)\MozillaFirefox\firefox.exe")
driver = webdriver.Firefox(firefox_binary=firefox) #建立Firefox瀏覽器的驅動執行個體

driver.implicitly_wait(2)#設定等待時間(定義執行步驟的逾時時間)
driver.maximize_window()  #最大化瀏覽器


driver.get("https://www.cnblogs.com/") #開啟部落格園首頁
search_field =driver.find_element_by_id('zzk_q') #通過id定位部落格園首頁的搜尋方塊
search_btn=driver.find_element_by_class_name('search_btn') #通過class定位部落格園首頁的查詢按鈕

search_field.clear() #清空搜尋方塊的值(如果有)
search_field.send_keys("python") #在搜尋方塊中輸入查詢條件
search_btn.click() #點擊查詢按鈕
# search_field.submit()
#選取<h3><a>開始 ,</a>結束之間的值,返回一個列表
products =driver.find_elements_by_xpath('//h3[a/@target="_blank"]/a')
#迭代列表products,輸出text的值
for p in products:
    print(p.text)
#選取<a target="_blank">節點的值,返回一個列表
pro =driver.find_elements_by_xpath('//h3/a[@target="_blank"]')
#迭代輸出href屬性的值
for p in pro:
    print(p.get_attribute('href'))
#關閉瀏覽器
driver.quit()

(三)  輸出如下

 

第二步驟中的xpth其實主要定位的就是下面這些

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.