python3初識selenium


第一步:安裝與配置

1.電腦上需要有火狐瀏覽器(默認安裝在C:\Program Files (x86)\Mozilla Firefox目錄下)。

2.使用pip install selenium安裝好之后。

3.在這里https://github.com/mozilla/geckodriver/releases下載一個driver包,根據自己的系統決定下哪個,我下的是geckodriver-v0.11.1-win64.zip

4.把剛下好的包里面的exe文件拷貝到火狐瀏覽器目錄下,然后把火狐瀏覽器的目錄加入系統的環境變量里的PATH。

 

第二步:啟動python,測試selenium

Example 0:

open a new Firefox browser
load the page at the given URL
from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://seleniumhq.org/')
Example 1:

open a new Firefox browser
load the Yahoo homepage
search for “seleniumhq”
close the browser
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

browser.get('http://www.yahoo.com')
assert 'Yahoo' in browser.title

elem = browser.find_element_by_name('p')  # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)

browser.quit()

更多例子,看官網:https://pypi.python.org/pypi/selenium/2.45.0

PS:最好用的一點是,可以通過browser.page_source來獲得網頁源碼,傳進BeautifulSoup里就可以啦~~~~~

 

PPS:當然,如果想操作chrome同樣也是可以的,這時候需要一個chromedriver.exe,這個文件我是從這里下的:http://chromedriver.storage.googleapis.com/index.html?path=2.25/我下的是chromedriver_win32.zip。然后把里面的exe文件放進chrome的安裝目錄下,然后再把這個目錄加入PATH就可以使用了。我的chrome安裝目錄是C:\Program Files (x86)\Google\Chrome\Application。

測試代碼:

from selenium import webdriver

driver =  webdriver.Chrome()

driver.get("http://www.baidu.com")

driver.quit()

 

PPPS:然后,在使用的時候發現有時候會有頁面加載很慢的情況,因為selenium是在頁面完全加載完畢才會停止,然而這個在很多時候是沒有必要的,這個時候可以自己手動設置超時時間。方法如下:(參考https://my.oschina.net/u/2344787/blog/400507?p={{page}})

 
         
from selenium import webdriver
from selenium.common.exceptions import TimeoutException

driver = webdriver.Firefox()
# 設定頁面加載限制時間
driver.set_page_load_timeout(5)
driver.maximize_window()

try:
    driver.get('http://www.icourse163.org/')
except TimeoutException:  
    driver.execute_script('window.stop()') #當頁面加載時間超過設定時間,通過執行Javascript來stop加載,即可執行后續動作

 

一個例子:抓取中國裁判文書網

from selenium import webdriver
from bs4 import BeautifulSoup
import time

d = webdriver.Chrome()
d.get("http://wenshu.court.gov.cn/list/list/?sorttype=1&conditions=searchWord+QWJS+++全文檢索:搶劫")
time.sleep(5) # 根據網絡情況調整sleep時間
d.execute_script("""
var span = document.createElement(\"span\");
span.id = \"myspanspan\";
span.innerHTML = document.getElementById(\"resultList\").innerHTML;
var ele = document.body;
ele.appendChild(span);
""")
soup = BeautifulSoup(d.page_source,'html.parser',from_encoding='gb18030')
x = soup.find('span',{'id':'myspanspan'})
print(str(x))
d.close()

 


免責聲明!

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



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