開始使用免費開始

超連結啟動

在進行「網頁爬取」時,最重要要擷取的屬性之一,是 a 標籤中的超連結網址(href 屬性)。這裡你將會擷取這個超連結!我們已經建立 print_attribute 函式,用來印出你用 XPath 擷取到的資料,所以如果你想,你可以在主控台測試你的 XPath 字串。

本練習使用以下 HTML 原始碼:

<html>
  <body>
    <div id="div1" class="class-1">
      <p class="class-1 class-2">Hello World!</p>
      <div id="div2">
        <p id="p2" class="class-2">Choose 
            <a href="http://datacamp.com">DataCamp!</a>!
        </p>
      </div>
    </div>
    <div id="div3" class="class-2">
      <p class="class-2">Thanks for Watching!</p>
    </div>
  </body>
</html>

本練習屬於課程

Python 網頁爬蟲

檢視課程

練習說明

  • 填入空格,完成下面的變數 xpath,以選取 DataCamp 超連結的 href 屬性值。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Create an xpath to the href attribute
xpath = '//p[@id=____]/a/____'

# Print out the selection(s); there should be only one
print_attribute( xpath )
編輯並執行程式碼