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

相关推荐
q***d1739 分钟前
Kotlin在后台服务中的框架
android·开发语言·kotlin
周杰伦fans16 分钟前
C# 中的 `Hashtable`
开发语言·c#
习习.y21 分钟前
关于python中的面向对象
开发语言·python
lingggggaaaa21 分钟前
免杀对抗——C2远控篇&PowerShell&有无文件落地&C#参数调用&绕AMSI&ETW&去混淆特征
c语言·开发语言·笔记·学习·安全·microsoft·c#
技术净胜22 分钟前
MATLAB 基因表达数据处理与可视化全流程案例
开发语言·matlab
友友马22 分钟前
『Qt』多元素控件
开发语言·qt
hmbbcsm30 分钟前
练习python题目小记(六)
开发语言·python
wow_DG38 分钟前
【Python✨】VS Code 秒开 Python 类型检查:一招 mypy + settings.json 让你的 Bug 原地现形!
python·json·bug
4***V2021 小时前
Vue3响应式原理详解
开发语言·javascript·ecmascript
q***98521 小时前
VS Code 中如何运行Java SpringBoot的项目
java·开发语言·spring boot