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

相关推荐
lsx20240613 小时前
JavaScript Array(数组)
开发语言
小柯博客13 小时前
Amazon Kinesis Video Streams C WebRTC SDK 开发实战
c语言·开发语言·网络·stm32·嵌入式硬件·webrtc·yocto
rannn_11113 小时前
3h速通Python:用Java的思维看懂Python
开发语言·python·ai·ai agent·大模型应用开发
qq_3721542313 小时前
Python中如何快速创建全零数组_使用NumPy的zeros函数初始化内存
jvm·数据库·python
上弦月-编程13 小时前
C语言位运算:从入门到精通
运维·c语言·开发语言·vscode·算法·leetcode·极限编程
2301_7965885013 小时前
Tailwind CSS如何快速实现居中对齐_使用mx-auto类实现CSS块级居中
jvm·数据库·python
minglie113 小时前
c语言面向对象的led
c语言·开发语言
码点滴13 小时前
上下文压缩不是“丢数据“:Context Compressor 的血缘追踪与 Prefix Cache 保护
人工智能·python·架构·prompt·ai编程
奇妙之二进制13 小时前
fastdds源码分析之WriterListener
linux·开发语言·dds
小园子的小菜13 小时前
生产实战|冷热数据转换:从识别、触发到落地全流程解析
java·开发语言·spring