【网络安全带你练爬虫-100练】第17练:分割字符串

目录

一、目标1:使用函数分割

二、目标2:使用函数模块

三、目标3:使用正则匹配


一、目标1:使用函数分割

目标:x.x.x.x[中国北京 xx云]

方法:split函数+replace函数


1、分割:使用split()方法将其按照"["进行分割,得到一个列表split_ip

2、元素:列表的第一个元素就是IP地址部分,第二个元素是包含位置信息的字符串。

3、获取目标:通过索引split_ip[0]获取IP地址部分,将其赋值给变量ip。通过split_ip[1]获取位置信息部分

4、使用replace()方法去掉末尾的"]",将得到的结果赋值给变量location

python 复制代码
ip_address = "x.x.x.x[中国北京 xx云]"
split_ip = ip_address.split("[")
ip = split_ip[0]
location = split_ip[1].replace("]", "")

print("IP: ", ip)
print("Location: ", location)


二、目标2:使用函数模块

urlparse函数(urllib模块):可以解析URL并将其拆分为各个组成部分。然后将要截取域名的URL赋值给url变量

python 复制代码
from urllib.parse import urlparse

url = "https://www.example.com/path/page.html"

parsed_url = urlparse(url)
domain = parsed_url.netloc

print(domain) # 输出:"www.example.com"

三、目标3:使用正则匹配

正则匹配根据具体情况具体分析

python 复制代码
import re

# 假设data是你的数据包内容,可以是一个字符串或文本文件等
data = "This is a sample text with URLs like http://example.com and https://www.google.com"

# 定义URL匹配的正则表达式模式
pattern = r'(https?://\S+)'

# 使用findall()函数匹配所有URL
urls = re.findall(pattern, data)

# 打印提取到的URL
for url in urls:
    print(url)
相关推荐
czhc11400756632 分钟前
Linux 76 rsync
linux·运维·python
悠悠小茉莉32 分钟前
Win11 安装 Visual Studio(保姆教程 - 更新至2025.07)
c++·ide·vscode·python·visualstudio·visual studio
m0_625686551 小时前
day53
python
Real_man1 小时前
告别 requirements.txt,拥抱 pyproject.toml和uv的现代Python工作流
python
K哥爬虫2 小时前
【APP逆向百例】某品会 app 逆向分析
爬虫
站大爷IP2 小时前
Python文件操作的"保险箱":with语句深度实战指南
python
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
巴里巴气4 小时前
selenium基础知识 和 模拟登录selenium版本
爬虫·python·selenium·爬虫模拟登录
19894 小时前
【零基础学AI】第26讲:循环神经网络(RNN)与LSTM - 文本生成
人工智能·python·rnn·神经网络·机器学习·tensorflow·lstm
JavaEdge在掘金5 小时前
Redis 数据倾斜?别慌!从成因到解决方案,一文帮你搞定
python