如何用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

