python(一)网络爬取

在爬取网页信息时,需要注意网页爬虫规范文件robots.txt

eg:csdn的爬虫规范文件 csdn.net/robots.txt

User-agent:

下面的Disallow规则适用于所有爬虫(即所有用户代理)。星号*是一个通配符,表示"所有"。

Disallow:

禁止爬虫访问的路径

1、首先下载python的相关类库

python 复制代码
pip install requests
pip install beautifulsoup4

requests 是一个http库,可以发送网络请求 。

beautifulsoup4 主要用来解析html文档。

2、引入相关库

python 复制代码
import requests    
from bs4 import BeautifulSoup  

3、编写相关代码

python 复制代码
url = 'https://www.....com'    
response = requests.get(url)    
  
html_content = response.text  
soup = BeautifulSoup(html_content, 'html.parser')  
  
titles = soup.select('h2') 
for title in titles:  
    print(title.text)

url : 需要爬的页面路径

response = requests.get(url) 发送get请求并接受

html_content = response.text 取出页面主体

soup = BeautifulSoup(html_content, 'html.parser') 由beautifulsoup对主体中的h5标签解析

titles = soup.select('h2') 选择所有的h2标签

最后循环遍历打印出所有h2 标签

4、测试

相关推荐
chaofan98011 小时前
GPT-5.5 全压力测试:为什么 API 聚合调度是解决“首字延迟”的技术关键?
开发语言·人工智能·python·gpt·自动化·api
才兄说11 小时前
机器人二次开发机器人动作定制?定制化舞蹈
python
William_wL_11 小时前
【C++】stack和queue的使用和实现(附加deque的简单介绍)
开发语言·c++
曲幽11 小时前
FastAPI配置管理避坑指南:从硬编码到 .env 与 pydantic_settings 类,连路由用法都给你捋清楚
python·fastapi·web·settings·config·pydantic·.env·dotenv·.env.prod
hhb_61811 小时前
D架构底层调度与性能优化实践指南
开发语言
淘矿人11 小时前
2026年4月-DeepSeek V4 vs GPT-5.5深度对比测评:weelinking一键切换实测
服务器·数据库·人工智能·python·gpt·学习·php
秋911 小时前
Java AI编程工具全景解析:功能、收费与工单系统实战指南
java·开发语言·ai编程
会编程的土豆11 小时前
【go】 Go语言中的 defer:从入门到理解底层机制(讲透版)
开发语言·后端·golang
一只幸运猫.11 小时前
Google Mug库——一个现代的通用工具库
开发语言·python
2401_8314194411 小时前
CSS 悬停箭头闪烁下移问题的根源与稳定解决方案
jvm·数据库·python