You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用BeautifulSoup Python 3.x提取子元素的href属性?

使用BeautifulSoup提取HTML中a标签的href属性

嘿,我来帮你搞定这个问题,用BeautifulSoup提取这些href属性其实很简单,跟着下面的步骤来就行~

第一步:先装好依赖

如果你还没安装BeautifulSoup4和requests(如果是处理本地HTML字符串,requests可以不用,但爬取网页时需要),先执行这个命令安装:

pip install beautifulsoup4 requests

第二步:编写提取代码

我把你提供的HTML补全了缺失的闭合标签,直接看代码示例:

from bs4 import BeautifulSoup

# 你的HTML内容(补全后)
html_content = """
<div class="search_col_2"> 
    <h2><a href="/profile.php?id=2323232">Maahsuj akisak</a><span class="for-complete-profile"> </span> </h2> 
</div>
<div class="search_col_2"> 
    <h2><a href="/profile.php?id=23232">Nunapu akisak</a><span class="for-complete-profile"> </span> </h2> 
</div>
<div class="search_col_2"> 
    <h2><a href="/profile.php?id=2323332">Rahenu Kahiske</a><span class="for-complete-profile"> </span> </h2> 
</div>
"""

# 用Python内置的html.parser解析HTML
soup = BeautifulSoup(html_content, 'html.parser')

# 方法一:按标签层级一步步查找
# 先抓取所有class为search_col_2的div
target_divs = soup.find_all('div', class_='search_col_2')
for div in target_divs:
    # 从div里找到h2,再定位里面的a标签
    link_tag = div.find('h2').find('a')
    # 获取href属性,用get()更安全,避免标签无href时报错
    href_value = link_tag.get('href')
    print(href_value)

print("--- 分割线 ---")

# 方法二:用CSS选择器,更简洁高效
# 直接选中所有.search_col_2下的h2内的a标签
all_links = soup.select('.search_col_2 h2 a')
for link in all_links:
    print(link.get('href'))

运行结果

执行代码后,你会得到所有目标href值:

/profile.php?id=2323232
/profile.php?id=23232
/profile.php?id=2323332
--- 分割线 ---
/profile.php?id=2323232
/profile.php?id=23232
/profile.php?id=2323332

小提示

  • 为什么用class_而不是class?因为class是Python的关键字,所以BeautifulSoup用class_来指定元素的class属性。
  • 推荐用get('href')而非直接link_tag['href']:万一某个a标签没有href属性,get()会返回None,而直接取值会抛出KeyError,容错性更强。
  • CSS选择器是处理复杂HTML结构的利器,如果你熟悉CSS语法,用soup.select()会大幅提升提取效率。

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

火山引擎 最新活动