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

如何用BeautifulSoup替换href中的ä为%c3%a4以修复无效链接

问题

我编写了如下Python代码,目前运行正常,但最后两个href属性中包含字符“ä”,导致链接无法正常访问。请问如何将这些href中的“ä”替换为“%c3%a4”,以确保能打开正确的网站?

代码:

import requests
from bs4 import BeautifulSoup

url = "https://www.gelbeseiten.de/"
req = requests.get(url)
src = req.text
soup = BeautifulSoup(src, "lxml")

all_categories = soup.find_all("a", class_="gc-link gc-link--blue")
for i in all_categories:
    print("https://www.gelbeseiten.de" + i.get("href"))
解决方案

不要手动替换特殊字符,直接用Python标准库urllib.parse里的quote方法对URL路径部分进行编码,这样能自动处理所有非ASCII字符(包括“ä”这类德语特殊字符),比手动替换更可靠。

修改后的代码如下:

import requests
from bs4 import BeautifulSoup
from urllib.parse import quote

url = "https://www.gelbeseiten.de/"
req = requests.get(url)
src = req.text
soup = BeautifulSoup(src, "lxml")

all_categories = soup.find_all("a", class_="gc-link gc-link--blue")
for i in all_categories:
    # 对href部分进行URL编码
    encoded_href = quote(i.get("href"))
    full_url = f"https://www.gelbeseiten.de{encoded_href}"
    print(full_url)

补充说明

  • quote方法会自动将“ä”转换为%c3%a4,同时也能处理其他类似的特殊字符(比如“ö”“ü”等),避免遗漏个别字符导致的链接失效。
  • 若需编码包含查询参数的完整URL,可使用quote_plus方法,但针对当前场景,quote足以满足需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:02:16