在Python中用Selenium執行JavaScript

來源:互聯網
上載者:User

標籤:head   phantomjs   網站   blog   page   網路爬蟲   rom   path   color   

Selenium自己不帶瀏覽器, 需要與第三方瀏覽器結合在一起使用.例如在Firefox上運行Selenium.

PhantomJS是一個"無頭"瀏覽器. 它會把網站載入到記憶體並執行頁面上的JavaScript, 但是它不會向使用者展示網頁的圖形介面. 把Selenium和PhantomJS結合在一起, 就可以運行一個非常強大的網路爬蟲了, 可以處理cookie, JavaScript,header, 以及任何你需要做的事.

Selenium可以從PyPI網站(https://pypi.python.org/simple/selenium)下載Selenium庫, 也可以用pip安裝.

PhantomJS可以從官網下載(http://phantomjs.org/download.html) , PhantomJS不是一個Python庫,不能用pip安裝.

1 from selenium import webdriver2 import time3 4 driver = webdriver.PhantomJS(executable_path=‘ ‘)5 driver.get("http://pythonscraping.com/pages/javascript/ajaxDemo.html")6 time.sleep(3)7 print(driver.find_element_by_id(‘content‘).text)8 driver.close()

executable_path變數值為phantomjs.exe的路徑. 如: executable_path = ‘/download/phantomjs-2.1.1-windows/bin/phantomjs‘

selenium的選取器都是用了非常直截了當的名稱, 上面的例子, 也可以用如下的選取器:

driver.find_element_by_css_selector("#content")

driver.find_element_by_tag_name("div")

另外, 如果你還是想用BeautifulSoup來解析網頁內容, 可以用WebDriver的page_source函數返回頁面的原始碼字串.

1 pageSouce = driver.page_source2 bsObj = BeautifulSoup(pageSource)3 print(bsObj.find(id="content").get_text())

 

在Python中用Selenium執行JavaScript

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.