【网络安全带你练爬虫-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 3.10+
开发语言·人工智能·python
梦想不只是梦与想7 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波7 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
copyer_xyf8 小时前
Python 异常处理
前端·后端·python
麻雀飞吧8 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy8 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.9 小时前
【01】Python 机器学习
开发语言·python
为爱停留9 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python
l1t9 小时前
DeepSeek总结的使用实体-组件-系统和基于存在性处理进行Python编程39-40
开发语言·python
曾阿伦9 小时前
Python 搭建简易HTTP服务
开发语言·python·http