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

相关推荐
阿正呀14 分钟前
Redis怎样实现本地缓存的高效失效通知
jvm·数据库·python
九转成圣21 分钟前
Java 性能优化实战:如何将海量扁平数据高效转化为类目字典树?
java·开发语言·json
SmartRadio25 分钟前
ESP32-S3 双模式切换实现:兼顾手机_路由器连接与WiFi长距离通信
开发语言·网络·智能手机·esp32·长距离wifi
2501_9012005330 分钟前
mysql如何设置InnoDB引擎参数_优化innodb_buffer_pool
jvm·数据库·python
laowangpython38 分钟前
Rust 入门:GitHub 热门内存安全编程语言
开发语言·其他·rust·github
我叫汪枫42 分钟前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
_.Switch44 分钟前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
软件技术NINI44 分钟前
webkit简介及工作流程
开发语言·前端·javascript·udp·ecmascript·webkit·yarn
Brendan_00144 分钟前
JavaScript的Stomp.over
开发语言·javascript·ecmascript
念2341 小时前
f5 shape分析
开发语言·javascript·ecmascript