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 小时前
【Appium 系列】第10节-手势操作实战 — 滑动、拖拽、缩放与轻拂
linux·服务器·开发语言·人工智能·python·appium·pytest
雪度娃娃14 小时前
转向现代C++——在创建对象时注意区分()和{}
开发语言·c++
Wanderer X14 小时前
【代码】hot100
python
铅笔小新z14 小时前
【C语言】数组详解
c语言·开发语言
摇滚侠14 小时前
Java 饿汉式 单例模式
java·开发语言·单例模式
hahdbk14 小时前
口碑好的医疗设备外观设计选哪家
大数据·人工智能·python
lbb 小魔仙14 小时前
工业数据困局的破局者:DolphinDB 如何让海量时序数据真正“跑“出价值
开发语言·人工智能·python·langchain
2301_7838486514 小时前
JavaScript中利用Symbol实现单例模式的属性锁定
jvm·数据库·python
枫叶丹414 小时前
【HarmonyOS 6.0】Device Security Kit安全审计阻断功能深度解析
开发语言·安全·华为·harmonyos
读书札记202214 小时前
C++ switch..case语句中变量跨域问题探讨及解决方法
开发语言·c++