14.5. Plan 4: Get info from a single tag¶
14.5.1. Plan 4: Example¶
Maybe we want to get just one piece of information from a webpage. In this example, we want to get the first link to a news story from a professor’s page.
Here’s what we see when we use the “inspect” function in the browser.
Since that tag is the first of its type on the page, we can use the plan Get info from a single tag.
Goal: Get info from a single tag# Get first tag of a certain type from the soup tag = soup.find('a', class_='item-teaser--heading-link') # Get info from tag info = tag.get('href')
14.5.2. Plan 4: When to use it¶
Use this when you want to get information that is in the first tag of a certain type on the page.
14.5.3. Plan 4: How to use it¶
Once you’ve found the tag you want to get information from, do two things:
Find the tag description and put it into the first slot.
How do you do that? Here are some examples:
What you see when you inspect |
Tag description in the code |
|
---|---|---|
|
-> |
|
|
-> |
|
|
-> |
|
|
-> |
|
|
-> |
|
Determine if you want to get text from a tag, or a link from a tag
The info you want |
What you put in the code |
|
---|---|---|
The tag’s text |
-> |
|
The tag’s link |
-> |
|
One type of tag, the a
tag, holds a link.
Here is the tag that creates the link to the North Quad dining hall page. It is an ‘a’ tag.
If you want to get the link from a tag, use get('href')
in the second slot in this plan.
14.5.4. Plan 4: Exercises¶
-
No, this is the full link, but there is a relative link in the tag.
/people/barbara-ericson
-
Correct!
a
-
No, this is the name of the tag
Barbara Ericson
-
No, this is the text of the tag
Q-1: What is the link of the tag below?
# Get first tag of a certain type from the soup tag = soup.find('div', class_='Comments_StyledComments-dzzyvm-0 dvnRbr') # Get info from tag info = tag.text
Check out the image below, that inspects the description of the North Quad dining hall.
Choose the subgoals that get the text from the tag that has the description of the North Quad dining hall, and put them in the right order. You do not need to use all the blocks.