欢迎光临
我们一直在努力

Python简易爬虫实现(requests+BeautifulSoup)

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */
#content_views .toc,
/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */
#content_views.markdown_views > p:empty:has(+ .toc),
#content_views.markdown_views > .toc + p:empty,
/* 富文本旧版目录标记 */
#content_views.htmledit_views #main-toc,
#content_views.htmledit_views #hr-toc,
#content_views.htmledit_views p[id*=\”-toc\”] {
display: none !important;
}
/* 目录去掉后,紧跟的首个标题不再多出一块上边距 */
#content_views.markdown_views > .toc + h1,
#content_views.markdown_views > .toc + h2,
#content_views.markdown_views > .toc + h3,
#content_views.markdown_views > .toc + h4,
#content_views.markdown_views > .toc + p:empty + h1,
#content_views.markdown_views > .toc + p:empty + h2,
#content_views.markdown_views > .toc + p:empty + h3,
#content_views.markdown_views > .toc + p:empty + h4 {
margin-top: 0 !important;
}

CSDN完整博文(直接全选复制,粘贴发布)

标题:Python简易爬虫实现(requests+BeautifulSoup)

一、前言

本文借助AI工具编写一个简单网页爬虫,使用requests库发起网络请求,BeautifulSoup解析HTML页面,获取网页标题。爬虫学习需要遵守网站robots协议,仅用于学习实验,禁止恶意爬取。

二、环境准备需要提前安装第三方库,打开命令行执行:
pip install requests beautifulsoup4
三、完整代码

import requests
from bs4 import BeautifulSoup

# 目标网页地址
url = "https://www.baidu.com"
# 请求头,模拟浏览器访问
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}

# 发送get请求
resp = requests.get(url, headers=headers)
# 自动识别网页编码
resp.encoding = resp.apparent_encoding

# 构造解析对象
soup = BeautifulSoup(resp.text, "html.parser")
# 提取title标签内容
title = soup.find("title")

# 输出结果
print("网页标题:", title.text)

四、代码解析

1. import requests:导入网络请求库,用来向网页发送请求,获取网页源码。

2. from bs4 import BeautifulSoup:导入网页解析工具,用来解析HTML文本,提取页面信息。

3. headers请求头:设置User-Agent伪装成浏览器,很多网站会拒绝没有UA的程序访问,加上可以避免简单反爬拦截。

4. requests.get():发送GET请求,拿到网页的响应内容。

5. resp.encoding:设置编码,防止中文乱码。

6. BeautifulSoup(resp.text, "html.parser"):把网页源码交给解析器,生成soup对象。

7. soup.find("title"):查找页面中第一个title标签,获取网页标题。

五、运行结果

运行程序,控制台输出:
网页标题:百度一下,你就知道
六、爬虫注意事项

1. 爬虫仅限课程学习使用,不能高频、大规模爬取网站;

2. 遵守目标网站robots协议,不爬取个人隐私、付费内容;

3. 不要用于商业用途,避免法律风险。

赞(0)
未经允许不得转载:171主机测评 » Python简易爬虫实现(requests+BeautifulSoup)
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址