隱藏連結
我們已經載入一個祕密網站的 HTML,並用它建立了 how_many_elements() 與 preview() 這兩個函式。how_many_elements() 讓你傳入一個 XPath 字串,並列印出你寫的 XPath 所選到的元素數量。preview() 讓你傳入一個 XPath 字串,並列印出你選到的前幾個元素。
你在本練習的任務是建立一個 XPath,能夠導向所有超連結 a 元素中,其 class 屬性包含字串 "dropdown__link" 的 href 屬性值。若你寫對了,應該會發現你的 XPath 字串選到了 4 個元素,且預覽顯示的是連結。
本練習屬於課程
Python 網頁爬蟲
練習說明
- 在下方填空,把一個 XPath 字串指派給變數
xpath,使其能導向所有超連結a元素中,class 屬性包含字串"dropdown__link"的href屬性值。記得在 XPath 字串中使用contains來檢查屬性值是否包含特定字串。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Create an xpath to the href attributes
xpath = '//a[contains(____,____)]/____'
# Print out how many elements are selected
how_many_elements( xpath )
# Preview the selected elements
preview( xpath )