1. 程式人生 > 實用技巧 >爬蟲-xpath的應用(6)

爬蟲-xpath的應用(6)

什麼是xpath

1】xpath使用路徑表示式在xml和html中進行導航
2】xpath包含標準庫
3】xpath是一個w3c的標準

在本文將會利用scrapy的select實現。故而將會安裝以下的依賴包

pip install twisted
pip install lxml
pip install scrapy
注意在安裝lxml的時候會出現依賴的處理得問題。可以安裝vscode來進行處理

xpath的節點關係

父親節點
子節點
同胞節點
先輩節點
後代節點

xpath語法【xpath的外掛安裝方式,我的部落格前面也有】

程式碼實現與解析:

html = """
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>bobby基本資訊</title> <script src="//code.jquery.com/jquery-1.11.3.min.js"></script> </head> <body> <div id="info"> <p style="color: blue">講師資訊</p> <div class="teacher_info info"> python全棧工程師,7年工作經驗,喜歡鑽研python技術,對爬蟲、 web開發以及機器學習有濃厚的興趣,關注前沿技術以及發展趨勢。 <p class="age">年齡: 29</p> <p class="name bobbyname" data-bind="bobby bobby2">姓名: bobby</p> <p class="work_years">工作年限: 7年</p> <p class="position">職位: python開發工程師</p> </div> <p style="color: aquamarine">課程資訊</p> <table class="courses"> <tr> <th>課程名</th> <th>講師</th> <th>地址</th> </tr> <tr> <td>django打造線上教育</td> <td>bobby</td> <td><a href="https://coding.imooc.com/class/78.html">訪問</a></td> </tr> <tr> <td>python高階程式設計</td> <td>bobby</td> <td><a href="https://coding.imooc.com/class/200.html">訪問</a></td> </tr> <tr> <td>scrapy分散式爬蟲</td> <td>bobby</td> <td><a href="https://coding.imooc.com/class/92.html">訪問</a></td> </tr> <tr> <td>django rest framework打造生鮮電商</td> <td>bobby</td> <td><a href="https://coding.imooc.com/class/131.html">訪問</a></td> </tr> <tr> <td>tornado從入門到精通</td> <td>bobby</td> <td><a href="https://coding.imooc.com/class/290.html">訪問</a></td> </tr> </table> </div> </body> </html>
""" from scrapy import Selector sel = Selector(text=html) #注意標籤的順序是重1開始的,不是0 name_xpath = "//div[1]/div[1]/p[2]/text()" #獲取使用者名稱字 name = "" #extract,是將資料提取出來同時轉化為字串 tag_texts = sel.xpath(name_xpath).extract() if tag_texts: name = tag_texts[0] print(name) #教師資訊 teacher_tag = sel.xpath("//div[@class='teacher_info info']/p
") #使用contains函式可以實現僅僅匹配一個型別 teacher_tag1 = sel.xpath("//div[contains(@class, 'teacher_info')]/p")