通过使用 python 的 requests 和 beautifulsoup 库,可以从百度上爬取网页。步骤如下:安装 requests 和 beautifulsoup 库。发送 http get 请求到目标网页。使用 beautifulsoup 解析获取的 html 内容。使用选择器方法提取所需数据。保存或处理提取的数据。
如何使用 Python 从百度上爬取网页
步骤:
-
安装必要的库:
- requests:发送 HTTP 请求。
- BeautifulSoup:解析 HTML 内容。
-
发送 HTTP 请求:
立即学习“Python免费学习笔记(深入)”;
- 使用 requests.get() 发送 GET 请求到目标网页。
- 例如,要爬取百度首页,可以使用以下代码:
import requests
response = requests.get("https://www.baidu.com")
-
解析 HTML 内容:
- 使用 BeautifulSoup 解析获取的 HTML 内容。
- 例如,要获取百度首页的标题,可以使用以下代码:
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
title = soup.find("title").text
-
提取所需数据:
- 使用 BeautifulSoup 的选择器方法提取所需数据。
- 例如,要获取百度首页上的所有链接,可以使用以下代码:
links = soup.find_all("a", href=True)
for link in links:
print(link["href"])
-
保存或处理数据:
- 根据需要保存或处理提取的数据。
- 可以将数据保存到文件、数据库或进行进一步处理。
示例代码:
import requests
from bs4 import BeautifulSoup
# 发送请求
response = requests.get("https://www.baidu.com")
# 解析 HTML
soup = BeautifulSoup(response.text, "html.parser")
# 提取标题
title = soup.find("title").text
print(f"页面标题:{title}")
# 提取所有链接
links = soup.find_all("a", href=True)
for link in links:
print(link["href"])
幻夢星雲 
![[爱了]](/js/img/d1.gif)
![[尴尬]](/js/img/d16.gif)