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

相关推荐
比奇堡的猪猪几秒前
修改默认conda环境(在win中)
python·conda
天府之绝2 分钟前
uniapp 中使用uview表单验证时,自定义扩展的表单,在改变时无法触发表单验证处理;
开发语言·前端·javascript·vue.js·uni-app
萧鼎11 分钟前
深入解析 Python 的 Word 模板引擎:docxtpl 全面指南
开发语言·python·word
Chan1613 分钟前
场景题:如何设计一个分布式ID
java·开发语言·spring boot·java-ee·intellij-idea
Yeats_Liao18 分钟前
昇腾910B与DeepSeek:国产算力与开源模型的架构适配分析
人工智能·python·深度学习·神经网络·机器学习·架构·开源
chamu9919 分钟前
C++ 的可调用对象
开发语言·c++
tianyuanwo19 分钟前
Bash与Sh的诞生背景、底层原理及Linux多Shell解释器兼容性解析
linux·开发语言·bash
智航GIS21 分钟前
11.3 Pandas 模块功能概览
python·信息可视化·pandas
浩子智控21 分钟前
开源RPA选择
python·c#·软件工程
kszlgy23 分钟前
Day48 随机函数与广播机制
python