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、测试

相关推荐
鲤鱼不懂9 分钟前
python 浅拷贝copy与深拷贝deepcopy 理解
开发语言·python
六边形战士DONK11 分钟前
0_Pytorch中的张量操作
人工智能·pytorch·python
猫猫头有亿点炸27 分钟前
C语言之九九乘法表
c语言·开发语言
问道飞鱼39 分钟前
【Vue3知识】组件间通信的方式
开发语言·javascript·ecmascript·组件·通信
yuweififi1 小时前
CBGSDataset类-带类别平衡采样的数据集封装器
python·深度学习·机器学习
树下水月1 小时前
关于使用python 安装 flask-openapi3扩展,使用docker 环境的完整复盘
开发语言·python·flask
时雨h1 小时前
《Spring Boot+策略模式:企业级度假订单Excel导入系统的架构演进与技术实现》
开发语言·bash
DreamNotOver1 小时前
PDF 中提取数学公式
python·pdf·提取公式
程序员JerrySUN1 小时前
驱动开发硬核特训 · Day 1
java·linux·运维·开发语言·c++·驱动开发
明明明h1 小时前
C#网络编程(Socket编程)
开发语言·网络·c#