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

相关推荐
大连好光景4 分钟前
批量匿名数据重识别(debug记录)
开发语言·python
计算机毕设VX:Fegn08955 分钟前
计算机毕业设计|基于Java + vue水果商城系统(源码+数据库+文档)
java·开发语言·数据库·vue.js·spring boot·课程设计
暴风鱼划水10 分钟前
算法题(Python)哈希表 | 2.两个数组的交集
python·算法·哈希表
清水白石00811 分钟前
《深入 Celery:用 Python 构建高可用任务队列的实战指南》
开发语言·python
Tony Bai15 分钟前
Jepsen 报告震动 Go 社区:NATS JetStream 会丢失已确认写入
开发语言·后端·golang
无敌最俊朗@19 分钟前
STL-list面试剖析(面试复习4)
开发语言
bing.shao21 分钟前
Golang 之 defer 延迟函数
开发语言·后端·golang
无敌最俊朗@24 分钟前
Qt 多线程编程: moveToThread 模式讲解
java·开发语言
!停29 分钟前
深入理解指针(4)
开发语言·javascript·ecmascript
小白狮ww31 分钟前
Matlab 教程:基于 RFUAV 系统使用 Matlab 处理无人机信号
开发语言·人工智能·深度学习·机器学习·matlab·无人机·rfuav