You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Python字符串变量中提取动态确认链接或其Token?

从HTML字符串中提取带动态Token的链接或Token

这里有两种可行的实现方法,根据你的场景选择:

方法一:正则表达式(快速直接)

如果HTML结构简单且链接格式固定,用正则可以快速提取目标内容:

import re

test = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><html><body><div dir="ltr"><p>test test test</p<p><ahref="https://test.com/users/confirmationconfirmation_token=XXXXXX">https://test.com/users/confirmation?confirmation_token=XXXXXX</a></p>\n<p>Link ile ilgili sorun yaşıyorsanız, kopyalayıp tarayıcınıza da yapıştırabilirsiniz.</p><p>Saygılarımızla,</p<p>test test test</p></div></body></html>'

# 提取完整链接
link_regex = re.compile(r'https://test\.com/users/confirmation\?confirmation_token=[A-Za-z0-9]+')
full_link = link_regex.search(test).group()
print(full_link)  # 输出完整链接

# 仅提取Token部分
token_regex = re.compile(r'confirmation_token=([A-Za-z0-9]+)')
token = token_regex.search(test).group(1)
print(token)  # 输出动态Token值

如果Token包含下划线、连字符等特殊字符,只需把正则里的[A-Za-z0-9]+调整为[A-Za-z0-9\-_]+即可适配。

方法二:HTML解析库(鲁棒性更强)

如果HTML结构可能变化或存在语法错误(比如你提供的字符串里<ahref>少了空格、<p>未闭合),用BeautifulSoup解析会更可靠:

from bs4 import BeautifulSoup
from urllib.parse import urlparse, parse_qs

test = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"><html><body><div dir="ltr"><p>test test test</p<p><ahref="https://test.com/users/confirmationconfirmation_token=XXXXXX">https://test.com/users/confirmation?confirmation_token=XXXXXX</a></p>\n<p>Link ile ilgili sorun yaşıyorsanız, kopyalayıp tarayıcınıza da yapıştırabilirsiniz.</p><p>Saygılarımızla,</p<p>test test test</p></div></body></html>'

# 解析HTML内容
soup = BeautifulSoup(test, 'html.parser')
# 获取a标签的文本内容(原HTML的href属性存在语法错误,文本里是正确链接)
a_tag = soup.find('a')
full_link = a_tag.get_text(strip=True)
print(full_link)

# 从链接中提取Token
parsed_url = urlparse(full_link)
token = parse_qs(parsed_url.query)['confirmation_token'][0]
print(token)

如果你的HTML是标准格式(<a href="正确链接">),可以直接用a_tag['href']获取链接,无需提取文本。


内容的提问来源于stack exchange,提问作者eymentakak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 16:57:33