抓取動態的網頁內容主要有兩種辦法,一種是通過開發者工具找到動態內容的接口,然后分析接口的參數和返回值來爬取網站的數據。另外一種是通過模擬瀏覽器來抓取數據。python的Selenium庫就可以通過代碼來模擬瀏覽器抓取數據。
一、概述
運行Selenium需要依賴于Python的selenium庫,以及瀏覽器對應驅動器(WebDriver)。
安裝selenium庫
pip install selenium
項目地址: https://pypi.org/project/selenium/
下載WebDriver
WebDriver可以簡單的理解為瀏覽器插件,是可執行的程序。不同的瀏覽器對應的WebDriver是不同的,比如火狐瀏覽器的WebDriver是geckodriver,Windows環境下是geckodriver.exe文件;Chrome瀏覽器的WebDriver是Chromedriver,Windows環境下是chromedriver.exe文件。
Webdriver下載之后解壓縮,將exe文件復制到python目錄下(只要目錄在path環境變量中就可以)
火狐的webdriver下載
https://github.com/mozilla/geckodriver/?
google chrome 的webdriver下載(按瀏覽器版本下載對應的webdriver,如果Chrome的版本與chromedriver.exe的版本不匹配,那么selenium的python程序會運行失敗的)
http://chromedriver.storage.googleapis.com/index.html
二、例子
例子1:
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://www.baidu.com')
assert '百度一下' in browser.title
#elem = browser.find_element_by_name("wd")
elem = browser.find_element_by_xpath('//*[@id="kw"]')
elem.send_keys("selenium")
btn = browser.find_element_by_id("su")
btn.click()
#browser.quit()
?
例子2:
import ?unittest
from selenium import webdriver
class BaiduTest(unittest.TestCase):
? ? def setUp(self):
? ? ? ? self.browser = webdriver.Firefox()
? ? ? ? self.browser.get("http://www.baidu.com")
? ? ? ? #self.addCleanup(self.browser.quit)
? ? def testTitle(self):
? ? ? ? self.assertIn("百度一下", self.browser.title)
? ? def testSearch(self):
? ? ? ? #self.browser.get("http://www.baidu.com")
? ? ? ? searchInput = self.browser.find_element_by_id("kw")
? ? ? ? searchInput.send_keys("selenium")
? ? ? ? searchBtn = self.browser.find_element_by_id("su")
? ? ? ? searchBtn.click()
? ? ? ? self.assertIn("selenium", self.browser.current_url)
if __name__ == '__main__':
? ? unittest.main(verbosity=2)
其他資源:
https://www.seleniumhq.org/download/
http://ftp.mozilla.org/pub/firefox/releases/ 火狐版本
https://www.cnblogs.com/givemelove/p/8482361.html 火狐、谷歌軟件及webdriver
本文內容到此結束,更多內容可關注公眾號和個人微信號:
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
