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

目录

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

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

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


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

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

方法:split函数+replace函数


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

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

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

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)
相关推荐
金銀銅鐵6 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1111 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0013 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵15 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf16 小时前
Agent 流程编排
后端·python·agent
copyer_xyf16 小时前
Agent RAG
后端·python·agent
copyer_xyf16 小时前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf17 小时前
Agent 记忆管理
后端·python·agent
星云穿梭1 天前
用Python写一个带图形界面的学生管理系统——完整教程
python