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

相关推荐
软件开发技术深度爱好者1 分钟前
Python库/包/模块管理工具
开发语言·python
bubiyoushang8889 分钟前
基于MATLAB的自然图像梯度分布重尾特性验证方案
开发语言·matlab
程序员爱钓鱼10 分钟前
Python 编程实战 · 进阶与职业发展:Web 全栈(Django / FastAPI)
后端·python·trae
MSTcheng.27 分钟前
【C++STL】priority_queue 模拟实现与仿函数实战
开发语言·c++
小年糕是糕手1 小时前
【C++】C++入门 -- inline、nullptr
linux·开发语言·jvm·数据结构·c++·算法·排序算法
郝学胜-神的一滴1 小时前
Python中一切皆对象:深入理解Python的对象模型
开发语言·python·程序人生·个人开发
csbysj20201 小时前
JSP 隐式对象
开发语言
星期天21 小时前
3.2联合体和枚举enum,还有动态内存malloc,free,calloc,realloc
c语言·开发语言·算法·联合体·动态内存·初学者入门·枚举enum
烤汉堡1 小时前
Python入门到实战:post请求和响应
python·html
梵克之泪2 小时前
【号码分离】从Excel表格、文本、word文档混乱文字中提取分离11位手机号出来,基于WPF的实现方案
开发语言·ui·c#