Beautiful Soup定位data-iso-code=inr的a标签报错及点击方法咨询
First, let's fix that BeautifulSoup error you're seeing, then cover how to interact with the element to click it.
Fixing the BeautifulSoup Selection Error
The SyntaxError pops up because Python doesn't allow keyword arguments with hyphens (like data-iso-code). Instead, you need to pass a dictionary to the attrs parameter when using find() or find_all().
Here's the corrected code to find the element:
from bs4 import BeautifulSoup # Assume your HTML content is stored in a variable called html_content soup = BeautifulSoup(html_content, 'html.parser') inr_currency_tag = soup.find('a', attrs={'data-iso-code': 'inr'}) # Verify you've found the right element by printing its text print(inr_currency_tag.text) # Output: ₹ - INR
If you need to find all elements with this attribute (not just the first), use find_all() instead:
all_inr_tags = soup.find_all('a', attrs={'data-iso-code': 'inr'})
Clicking the Element (Using Selenium)
BeautifulSoup only parses static HTML—it can't interact with live web pages or click elements. To actually click the button, you'll need a browser automation tool like Selenium. Here are a few reliable methods:
Method 1: CSS Selector (Most Straightforward)
Use the attribute directly in a CSS selector to target the element:
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Initialize your browser driver (example uses Chrome) driver = webdriver.Chrome() driver.get("your_target_page_url") # Wait for the element to be clickable (avoids race conditions) inr_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[data-iso-code="inr"]')) ) # Click the button inr_button.click() # Clean up: close the driver when done driver.quit()
Method 2: XPath
You can also use XPath to target the element by its attribute:
inr_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.XPATH, '//a[@data-iso-code="inr"]')) ) inr_button.click()
Method 3: Partial Link Text (If Text Is Consistent)
If the button text ("₹ - INR") doesn't change, you can use partial link text to locate it:
inr_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.PARTIAL_LINK_TEXT, "INR")) ) inr_button.click()
Note: Make sure you have Selenium installed (pip install selenium) and the correct web driver (like ChromeDriver) set up for your browser.
内容的提问来源于stack exchange,提问作者Mayank Soni

