1. 測試頁面是 https://www.hao123.com/,這個是百度的導航
2. 為了避免網絡請求帶來的差異,我們把網頁下載下來,命名為html,不粘貼其代碼。
3.測試辦法:
我們在頁面中找到 百度新聞 關鍵字的鏈接,為了能更好的對比,使程序運行10000次,比較時間差異:
1.正則編碼及其時間
start_time = time.time() for i in range(0,10000): baidu_news = re.findall('騰訊新聞</a></span><span><a class="sitelink mainlink singglelink" cls="xw,n" alog-custom="ind:xw,sal:0,atd:" href="(.*?)">百度新聞</a>',html)[0] print baidu_news end_time = time.time() print "程序運行時間是:",end_time - start_time
運行時間:6.5 秒鍾
2.xpath 編碼及其時間
start_time = time.time() selector = etree.HTML(html) for i in range(0,10000): content=selector.xpath('//*[@id="coolsite-top"]/div[4]/span[3]/a/@href')[0] print content end_time = time.time() print "程序運行時間是:",end_time - start_time
運行時間:17.39 秒鍾
總結:其中 selector = etree.HTML(html) 將源碼轉化為能被XPath匹配的格式,這個過程失比較耗時的。
結論:正則效率優於xpath
如有異議,請聯系作者,謝謝