1、引言
在Python網絡爬蟲內容提取器一文我們詳細講解了核心部件:可插拔的內容提取器類gsExtractor。本文記錄了確定gsExtractor的技術路線過程中所做的編程實驗。這是第二部分,第一部分實驗了用xslt方式一次性提取靜態網頁內容并轉換成xml格式。留下了一個問題:javascript管理的動態內容怎樣提?。磕敲幢疚木突卮疬@個問題。
2、提取動態內容的技術部件
在上一篇python使用xslt提取網頁數據中,要提取的內容是直接從網頁的source code里拿到的。但是一些Ajax動態內容是在source code找不到的,就要找合適的程序庫把異步或動態加載的內容加載上來,交給本項目的提取器進行提取。
python可以使用selenium執行javascript,selenium可以讓瀏覽器自動加載頁面,獲取需要的數據。selenium自己不帶瀏覽器,可以使用第三方瀏覽器如Firefox,Chrome等,也可以使用headless瀏覽器如PhantomJS在后臺執行。
3、源代碼和實驗過程
假如我們要抓取京東手機頁面的手機名稱和價格(價格在網頁源碼是找不到的),如下圖:

第一步:利用集搜客謀數臺的直觀標注功能,可以極快速度自動生成一個調試好的抓取規則,其實是一個標準的xslt程序,如下圖,把生成的xslt程序拷貝到下面的程序中即可。注意:本文只是記錄實驗過程,實際系統中,將采用多種方式把xslt程序注入到內容提取器重。

第二步:執行如下代碼(在windows10, python3.2下測試通過,源代碼下載地址請見文章末尾GitHub),請注意:xslt是一個比較長的字符串,如果刪除這個字符串,代碼沒有幾行,足以見得Python之強大
#/usr/bin/python from urllib import request from lxml import etree from selenium import webdriver import time # 京東手機商品頁面 url = "http://item.jd.com/1312640.html" # 下面的xslt是通過集搜客的謀數臺圖形界面自動生成的 xslt_root = etree.XML("""/ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" > <xsl:template match="/"> <商品> <xsl:apply-templates select="http://*[@id='itemInfo' and count(.//*[@id='summary-price']/div[position()=2]/strong/text())>0 and count(.//*[@id='name']/h1/text())>0]" mode="商品"/> </商品> </xsl:template> <xsl:template match="http://*[@id='itemInfo' and count(.//*[@id='summary-price']/div[position()=2]/strong/text())>0 and count(.//*[@id='name']/h1/text())>0]" mode="商品"> <item> <價格> <xsl:value-of select="*//*[@id='summary-price']/div[position()=2]/strong/text()"/> <xsl:value-of select="*[@id='summary-price']/div[position()=2]/strong/text()"/> <xsl:if test="@id='summary-price'"> <xsl:value-of select="div[position()=2]/strong/text()"/> </xsl:if> </價格> <名稱> <xsl:value-of select="*//*[@id='name']/h1/text()"/> <xsl:value-of select="*[@id='name']/h1/text()"/> <xsl:if test="@id='name'"> <xsl:value-of select="h1/text()"/> </xsl:if> </名稱> </item> </xsl:template> </xsl:stylesheet>""") # 使用webdriver.PhantomJS browser = webdriver.PhantomJS(executable_path='C://phantomjs-2.1.1-windows//bin//phantomjs.exe') browser.get(url) time.sleep(3) transform = etree.XSLT(xslt_root) # 執行js得到整個dom html = browser.execute_script("return document.documentElement.outerHTML") doc = etree.HTML(html) # 用xslt從dom中提取需要的字段 result_tree = transform(doc) print(result_tree)
新聞熱點
疑難解答