用 BeautifulSoup 将网页转为数据:获取超链接
本练习将带您从 BDFL 的网页中提取超链接的 URL。在此过程中,您会熟悉使用 soup 方法 find_all()。
本练习是课程的一部分
Python 数据导入进阶
练习说明
- 使用
find_all()方法在soup中查找所有超链接。请记住,超链接由 HTML 标签<a>定义,但传给find_all()时不带尖括号;将结果存入变量a_tags。 - 变量
a_tags是一个结果集。您的任务是使用for循环对其逐一遍历,并打印每个超链接的实际 URL。为此,对a_tags中的每个元素link,调用print()并传入link.get('href')。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import packages
import requests
from bs4 import BeautifulSoup
# Specify url
url = 'https://www.python.org/~guido/'
# Package the request, send the request and catch the response: r
r = requests.get(url)
# Extracts the response as html: html_doc
html_doc = r.text
# create a BeautifulSoup object from the HTML: soup
soup = BeautifulSoup(html_doc)
# Print the title of Guido's webpage
print(soup.title)
# Find all 'a' tags (which define hyperlinks): a_tags
# Print the URLs to the shell
for ____ in ____:
____