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

如何用BeautifulSoup提取含空格和换行的class对应的href属性

提取带空格/换行class的标签href属性

方法1:用class_参数传入类名列表

BeautifulSoup会自动忽略class属性里的换行、多空格,直接把class的所有拆分项作为列表传入class_参数即可定位标签:

from bs4 import BeautifulSoup

html = '''<a class="this is part1 
      this is part2" target="_self" href="https://www.website.com/">'''
soup = BeautifulSoup(html, 'html.parser')

target_link = soup.find('a', class_=['this', 'is', 'part1', 'this', 'is', 'part2'])
if target_link:
    print(target_link['href'])  # 输出:https://www.website.com/

方法2:使用CSS选择器

用.连接所有类名组成CSS选择器,不管原class里的空白符格式:

from bs4 import BeautifulSoup

html = '''<a class="this is part1 
      this is part2" target="_self" href="https://www.website.com/">'''
soup = BeautifulSoup(html, 'html.parser')

target_link = soup.select_one('a.this.is.part1.this.is.part2')
if target_link:
    print(target_link['href'])  # 输出:https://www.website.com/

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:30:38