从一次选择中再选择
在本练习中,您将从特定的 div 元素中找到一个 h4 元素的文本。操作分两步进行:首先选择一组 div 元素,其次缩小到第一个 div,然后从中获取 h4 元素的文本。这样逐步缩小定位范围(例如,先定位到 div 元素,再到 h4 元素)的过程也是一种"链式"选择,即使它的形式与之前看到的并不完全相同。
在本练习中,已为您准备了变量 first_div。请仔细思考 first_div 是什么类型的对象!
本练习是课程的一部分
Python Web 爬取
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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 )