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

Python函数占位符失效:page_url无法在正则表达式中生效

问题原因与修复方案

原因

你写的正则表达式里的{page_url}没有被解析成传入的参数值,核心问题是:

  • 你用了**原始字符串(r'')**但未搭配f-string语法,Python不会自动把{page_url}替换为变量值,正则会把{page_url}当作字面量字符串去匹配,自然找不到符合条件的链接。
  • 直接print(page_url)能正常输出是因为这是直接访问变量,和正则里的占位符解析逻辑完全无关。

修复方法

需要通过字符串格式化把page_url变量注入到正则表达式中,以下是两种常用实现方式:

方式1:使用f-string(推荐)

用rf''组合原始字符串与f-string特性,让占位符被正确解析:

import re
from bs4 import BeautifulSoup

def get_internal_links(soup, page_url):
    rtn_value = list()
    regex = re.compile(rf'^((https://)?{page_url}/|/).+')
    links = soup.find_all('a', {'href': regex})
    for link in links:
        try:
            href = link['href']
            rtn_value.append(href)
        except AttributeError:
            pass
    return rtn_value

方式2:使用str.format()

适配Python 3.5及更早版本的写法:

regex = re.compile(r'^((https://)?{}/|/).+'.format(page_url))

额外注意事项

如果page_url中包含.、*、?这类正则特殊字符,需要用re.escape()转义,避免这些字符被当作正则语法解析:

regex = re.compile(rf'^((https://)?{re.escape(page_url)}/|/).+')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:24:28