從選取中再選取
在這個練習中,你要在特定的 div 元素內找到一個 h4 元素的文字。這會分成幾個步驟:第一步先選取一組 div 元素,第二步縮小範圍到第一個 div,再從中抓取 h4 元素的文字。這種逐步縮小鎖定元素的做法(例如先到 div,再到 h4)就是「鏈結(chaining)」的另一個例子,即使看起來不完全和之前的一樣。
在這個練習中,已經幫你建立了一個變數 first_div 可供使用。請仔細思考 first_div 是哪一種類型的物件!
本練習屬於課程
Python 網頁爬蟲
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Select all desired div elements
divs = response.css(____)
# Take the first div element
first_div = divs[0]
# Extract the text from the (only) h4 element in first_div
h4_text = first_div.css(____).extract_first()
# Print out the text
print( "The text from the h4 element is:", h4_text )