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

相关推荐
程序猿_极客9 小时前
【2025 年最新版】Java JDK 安装与环境配置教程(附图文超详细,Windows+macOS 通用)
java·开发语言·windows·macos·jdk
二哈喇子!12 小时前
BOM模型
开发语言·前端·javascript·bom
二哈喇子!13 小时前
空指针异常
开发语言
咚为13 小时前
Rust Print 终极指南:从底层原理到全场景实战
开发语言·后端·rust
jaray13 小时前
PyCharm 2024.3.2 Professional 如何更换 PyPI 镜像源
ide·python·pycharm·pypi 镜像源
%xiao Q13 小时前
GESP C++五级-202406
android·开发语言·c++
Psycho_MrZhang13 小时前
Neo4j Python SDK手册
开发语言·python·neo4j
Traced back13 小时前
# C# + SQL Server 实现自动清理功能的完整方案:按数量与按日期双模式
开发语言·c#
sin220113 小时前
MyBatis的执行流程
java·开发语言·mybatis
web3.088899913 小时前
1688图片搜索API,相似商品精准推荐
开发语言·python