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

相关推荐
m0_743470376 分钟前
使用Python进行PDF文件的处理与操作
jvm·数据库·python
Dxy123931021616 分钟前
JS发送请求的方法详解
开发语言·javascript·ecmascript
sw12138927 分钟前
C++中的代理模式实战
开发语言·c++·算法
難釋懷37 分钟前
Lua语法入门-条件控制、函数
开发语言·junit·lua
桌面运维家1 小时前
Win10打印机共享故障排查:权限与网络配置详解
开发语言·网络·php
Sunshine for you1 小时前
实时操作系统中的C++
开发语言·c++·算法
史蒂芬_丁2 小时前
C++深度拷贝例子
java·开发语言·c++
数据科学小丫2 小时前
Python 数据存储操作_数据存储、补充知识点:Python 与 MySQL交互
数据库·python·mysql
Knight_AL2 小时前
Nacos 启动问题 Failed to create database ’D:\nacos\nacos\data\derby-data’
开发语言·数据库·python
leiming62 小时前
CAN 通信协议学习讲义(带图文 + C 语言代码)
c语言·开发语言·学习