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

如何用Python的BeautifulSoup选中指定链接?现有代码未获取目标链接

Hey there! Let's get that exact link you're targeting using BeautifulSoup. The issue with your original code is that it grabs every <a> tag with an href attribute, but we need to zero in on the specific one you want. Here are a few straightforward ways to do it:

1. Target the Exact Href Value

Since you know the precise URL you're looking for, you can use find() with the href parameter set directly to that URL:

from bs4 import BeautifulSoup

# Replace html_content with your actual parsed HTML
soup = BeautifulSoup(html_content, 'html.parser')

target_link = soup.find('a', href='https://www.jmir.org/2018/1/e1')
if target_link:
    print(target_link['href'])

This will locate the first (and likely only) <a> tag with that exact href value.

2. Use CSS Selectors for Precision

BeautifulSoup supports CSS selectors, which offer a clean way to target elements. You can select the link directly using its href attribute:

target_link = soup.select_one('a[href="https://www.jmir.org/2018/1/e1"]')
if target_link:
    print(target_link['href'])

select_one() returns the first matching element, which is perfect for grabbing this specific link.

3. Combine Class and Href (If Needed)

If there are multiple <a> tags with the "ng-binding" class, you can combine that with the href check to narrow things down further:

target_link = soup.find('a', class_='ng-binding', href='https://www.jmir.org/2018/1/e1')
if target_link:
    print(target_link['href'])

Note: We use class_ instead of class because "class" is a reserved keyword in Python.

Quick Heads-Up About Dynamic Content

Since the element has AngularJS attributes (ng-href, ng-bind-html), if you're scraping with just requests, the href might not populate in the initial HTML (AngularJS sometimes injects it dynamically after page load). If that's the case, you'd need a tool like Selenium to load the page fully before parsing it with BeautifulSoup. But based on the HTML snippet you shared, the href is already present, so the methods above should work smoothly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:28:37