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

相关推荐
gmaajt21 小时前
mysql如何检查数据库表是否存在损坏_使用CHECK TABLE命令修复
jvm·数据库·python
heRs BART21 小时前
【Flask】四、flask连接并操作数据库
数据库·python·flask
PyHaVolask1 天前
Python 爬虫进阶:直接请求 JSON 接口与开发者工具使用
爬虫·python·请求头·反爬·json接口·chrome开发者工具
larance1 天前
安装dify的几个问题
python
2301_773553621 天前
CSS如何对用户访问过的链接进行降级颜色处理_使用-visited伪类改变颜色
jvm·数据库·python
2301_815279521 天前
Golang怎么理解Go的sync.Pool底层_Golang如何理解Pool的本地缓存和GC清理机制【详解】
jvm·数据库·python
2301_764150561 天前
MySQL迁移过程如何避免数据不一致_利用强一致性备份方案
jvm·数据库·python
m0_716430071 天前
Redis如何处理预热失效引起的开局雪崩
jvm·数据库·python
m0_377618231 天前
c++文件锁使用方法 c++如何实现多进程文件同步
jvm·数据库·python
gmaajt1 天前
mysql多字段搜索如何设计组合索引_mysql索引查询加速
jvm·数据库·python