开始使用免费开始使用

使用 BeautifulSoup 将网页转为数据:提取文本

如前所述,接下来的练习将带您学习从 HTML soup 提取信息的基础操作。本练习中,您将提取 BDFL 网页中的文本,并打印网页标题。

本练习是课程的一部分

Python 数据导入进阶

查看课程

练习说明

  • 示例代码中已创建 HTML 响应对象 html_doc:您的首要任务是使用函数 BeautifulSoup() 将其转换为 soup,并将结果赋给变量 soup
  • 使用属性 title 从 HTML soup soup 中提取标题,并将结果赋给 guido_title
  • 使用 print() 函数在终端打印 Guido 网页的标题。
  • 使用方法 get_text() 从 HTML soup soup 中提取文本,并赋给 guido_text
  • 点击 Submit Answer 以在终端打印 Guido 网页的文本。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import packages
import requests
from bs4 import BeautifulSoup

# Specify url: url
url = 'https://www.python.org/~guido/'

# Package the request, send the request and catch the response: r
r = requests.get(url)

# Extract the response as html: html_doc
html_doc = r.text

# Create a BeautifulSoup object from the HTML: soup


# Get the title of Guido's webpage: guido_title


# Print the title of Guido's webpage to the shell


# Get Guido's text: guido_text


# Print Guido's text to the shell
print(guido_text)
编辑并运行代码