【网络安全带你练爬虫-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 小时前
Pydantic校验配置文件
python
hboot6 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi17 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi18 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽18 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户83580861879119 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L1 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅1 天前
海天线算法的前世今生
python·计算机视觉
韩师傅1 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L2 天前
LangGraph的MessageState and HumanMessage
python