Selecting from a Selection
In this exercise, you will find the text from an h4
element within a particular div
element. It will occur in steps where the first step is selecting a family of div
elements, and the second step is narrowing in on the first one, from which we will grab the h4
element text. This process of progressively narrowing in on elements (e.g., first to the div
elements, then to the h4
element) is another example of "chaining", even if it doesn't look exactly the same as we've seen it before.
Along the way in this exercise, there is a variable first_div
set up for you to use. Think carefully about what type of object first_div
is!
This exercise is part of the course
Web Scraping in Python
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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 )