動態網頁數據抓取
什么是AJAX:
AJAX(Asynchronouse JavaScript And XML)異步JavaScript和XML。過在后台與服務器進行少量數據交換,Ajax 可以使網頁實現異步更新。這意味着可以在不重新加載整個網頁的情況下,對網頁的某部分進行更新。傳統的網頁(不使用Ajax)如果需要更新內容,必須重載整個網頁頁面。因為傳統的在傳輸數據格式方面,使用的是XML語法。因此叫做AJAX,其實現在數據交互基本上都是使用JSON。使用AJAX加載的數據,即使使用了JS,將數據渲染到了瀏覽器中,在右鍵->查看網頁源代碼還是不能看到通過ajax加載的數據,只能看到使用這個url加載的html代碼。
獲取ajax數據的方式:
- 直接分析ajax調用的接口。然后通過代碼請求這個接口。
- 使用Selenium+chromedriver模擬瀏覽器行為獲取數據。
| 方式 |
優點 |
缺點 |
| 分析接口 |
直接可以請求到數據。不需要做一些解析工作。代碼量少,性能高。 |
分析接口比較復雜,特別是一些通過js混淆的接口,要有一定的js功底。容易被發現是爬蟲。 |
| selenium |
直接模擬瀏覽器的行為。瀏覽器能請求到的,使用selenium也能請求到。爬蟲更穩定。 |
代碼量多。性能低。 |
Selenium+chromedriver獲取動態數據:
Selenium相當於是一個機器人。可以模擬人類在瀏覽器上的一些行為,自動處理瀏覽器上的一些行為,比如點擊,填充數據,刪除cookie等。chromedriver是一個驅動Chrome瀏覽器的驅動程序,使用他才可以驅動瀏覽器。當然針對不同的瀏覽器有不同的driver。以下列出了不同瀏覽器及其對應的driver:
- Chrome:https://sites.google.com/a/chromium.org/chromedriver/downloads
- Firefox:https://github.com/mozilla/geckodriver/releases
- Edge:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/
- Safari:https://webkit.org/blog/6900/webdriver-support-in-safari-10/
- 安裝Selenium:Selenium有很多語言的版本,有java、ruby、python等。我們下載python版本的就可以了。
- pip install selenium
- 安裝chromedriver:下載完成后,放到不需要權限的純英文目錄下就可以了。
安裝Selenium和chromedriver:
快速入門:
from selenium import webdriver
# chromedriver的絕對路徑
driver_path = r'D:\ProgramApp\chromedriver\chromedriver.exe'
# 初始化一個driver,並且指定chromedriver的路徑
driver = webdriver.Chrome(executable_path=driver_path)
# 請求網頁
driver.get("https://www.baidu.com/")
# 通過page_source獲取網頁源代碼
print(driver.page_source)
selenium常用操作:
更多教程參考:http://selenium-python.readthedocs.io/installation.html#introduction
關閉頁面:
- driver.close():關閉當前頁面。
- driver.quit():退出整個瀏覽器。
定位元素:
要注意,find_element是獲取第一個滿足條件的元素。find_elements是獲取所有滿足條件的元素。
find_element_by_id:根據id來查找某個元素。等價於:
submitTag = driver.find_element_by_id('su')
submitTag1 = driver.find_element(By.ID,'su')
find_element_by_class_name:根據類名查找元素。 等價於:
submitTag = driver.find_element_by_class_name('su')
submitTag1 = driver.find_element(By.CLASS_NAME,'su')
find_element_by_name:根據name屬性的值來查找元素。等價於:
submitTag = driver.find_element_by_name('email')
submitTag1 = driver.find_element(By.NAME,'email')
find_element_by_tag_name:根據標簽名來查找元素。等價於:
submitTag = driver.find_element_by_tag_name('div')
submitTag1 = driver.find_element(By.TAG_NAME,'div')
find_element_by_xpath:根據xpath語法來獲取元素。等價於:
submitTag = driver.find_element_by_xpath('//div')
submitTag1 = driver.find_element(By.XPATH,'//div')
find_element_by_css_selector:根據css選擇器選擇元素。等價於:
submitTag = driver.find_element_by_css_selector('//div')
submitTag1 = driver.find_element(By.CSS_SELECTOR,'//div')
操作表單元素:
操作輸入框:分為兩步。第一步:找到這個元素。第二步:使用send_keys(value),將數據填充進去。示例代碼如下:
inputTag = driver.find_element_by_id('kw')
inputTag.send_keys('python')
使用clear方法可以清除輸入框中的內容。示例代碼如下:
inputTag.clear()
操作checkbox:因為要選中checkbox標簽,在網頁中是通過鼠標點擊的。因此想要選中checkbox標簽,那么先選中這個標簽,然后執行click事件。示例代碼如下:
rememberTag = driver.find_element_by_name("rememberMe")
rememberTag.click()
選擇select:select元素不能直接點擊。因為點擊后還需要選中元素。這時候selenium就專門為select標簽提供了一個類selenium.webdriver.support.ui.Select。將獲取到的元素當成參數傳到這個類中,創建這個對象。以后就可以使用這個對象進行選擇了。示例代碼如下:
from selenium.webdriver.support.ui import Select
# 選中這個標簽,然后使用Select創建對象
selectTag = Select(driver.find_element_by_name("jumpMenu"))
# 根據索引選擇
selectTag.select_by_index(1)
# 根據值選擇
selectTag.select_by_value("http://www.95yueba.com")
# 根據可視的文本選擇
selectTag.select_by_visible_text("95秀客戶端")
# 取消選中所有選項
selectTag.deselect_all()
操作按鈕:操作按鈕有很多種方式。比如單擊、右擊、雙擊等。這里講一個最常用的。就是點擊。直接調用click函數就可以了。示例代碼如下:
inputTag = driver.find_element_by_id('su')
inputTag.click()
行為鏈:
有時候在頁面中的操作可能要有很多步,那么這時候可以使用鼠標行為鏈類ActionChains來完成。比如現在要將鼠標移動到某個元素上並執行點擊事件。那么示例代碼如下:
inputTag = driver.find_element_by_id('kw')
submitTag = driver.find_element_by_id('su')
actions = ActionChains(driver)
actions.move_to_element(inputTag)
actions.send_keys_to_element(inputTag,'python')
actions.move_to_element(submitTag)
actions.click(submitTag)
actions.perform()
還有更多的鼠標相關的操作。
- click_and_hold(element):點擊但不松開鼠標。
- context_click(element):右鍵點擊。
- double_click(element):雙擊。 更多方法參考:http://selenium-python.readthedocs.io/api.html
Cookie操作:
獲取所有的cookie:
for cookie in driver.get_cookies():
print(cookie)
根據cookie的key獲取value:
value = driver.get_cookie(key)
刪除所有的cookie:
driver.delete_all_cookies()
刪除某個cookie:
driver.delete_cookie(key)
頁面等待:
現在的網頁越來越多采用了 Ajax 技術,這樣程序便不能確定何時某個元素完全加載出來了。如果實際頁面等待時間過長導致某個dom元素還沒出來,但是你的代碼直接使用了這個WebElement,那么就會拋出NullPointer的異常。為了解決這個問題。所以 Selenium 提供了兩種等待方式:一種是隱式等待、一種是顯式等待。
- 隱式等待:調用driver.implicitly_wait。那么在獲取不可用的元素之前,會先等待10秒中的時間。示例代碼如下
driver = webdriver.Chrome(executable_path=driver_path)
driver.implicitly_wait(10)
# 請求網頁
driver.get("https://www.douban.com/")
2/顯示等待:顯示等待是表明某個條件成立后才執行獲取元素的操作。也可以在等待的時候指定一個最大的時間,如果超過這個時間那么就拋出一個異常。顯示等待應該使用selenium.webdriver.support.excepted_conditions期望的條件和selenium.webdriver.support.ui.WebDriverWait來配合完成。示例代碼如下:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "myDynamicElement"))
)
finally:
driver.quit()
一些其他的等待條件:
- presence_of_element_located:某個元素已經加載完畢了。
- presence_of_all_emement_located:網頁中所有滿足條件的元素都加載完畢了。
- element_to_be_cliable:某個元素是可以點擊了。
更多條件參考:http://selenium-python.readthedocs.io/waits.html
切換頁面:
有時候窗口中有很多子tab頁面。這時候肯定是需要進行切換的。
selenium提供了一個叫做switch_to_window來進行切換,具體切換到哪個頁面,可以從driver.window_handles中找到。示例代碼如下:
# 打開一個新的頁面
self.driver.execute_script("window.open('https://www.baidu.com')")
#顯示當前頁面的url
driver.current_url //還是百度頁面
# 切換到這個新的頁面中
driver.switch_to_window(driver.window_handles[1])
設置代理ip:
有時候頻繁爬取一些網頁。服務器發現你是爬蟲后會封掉你的ip地址。這時候我們可以更改代理ip。更改代理ip,不同的瀏覽器有不同的實現方式。這里以Chrome瀏覽器為例來講解:
from selenium import webdriver
options = webdriver.ChromeOptions() //設置存儲瀏覽器的信息
//添加代理服務器
options.add_argument("--proxy-server=http://110.73.2.248:8123")
driver_path = r"D:\ProgramApp\chromedriver\chromedriver.exe"
driver = webdriver.Chrome(executable_path=driver_path,chrome_options=options)
driver.get('http://httpbin.org/ip')
WebElement元素:
from selenium.webdriver.remote.webelement import WebElement類是每個獲取出來的元素的所屬類。
有一些常用的屬性:
get_attribute:這個標簽的某個屬性的值。
screentshot:獲取當前頁面的截圖。這個方法只能在driver上使用。
driver的對象類,也是繼承自WebElement。
.
