如何用Python的BS4获取div标签的data-test5-uk属性值
Got it, let's fix this up and get that data-test5-uk value you need! First, let's clear up a couple of small issues and walk through the complete working code step by step.
First, a quick note: your original HTML has unclosed <a> and outer <div> tags, but BeautifulSoup is pretty forgiving and will auto-fix that during parsing, so no worries there.
Looking at your code snippet, the main issue is that you're initializing BeautifulSoup incorrectly (using size.text before that variable exists) and you missed that the data-test5-uk attribute lives on the <a> tag inside the <div>, not the div itself.
Here's the corrected, complete code:
from bs4 import BeautifulSoup # Your HTML content (I fixed the unclosed tags for clarity) html_content = ''' <div class="size "> <a class="selectSize" id="25746" data-ean="884751585616" data-test="170" data-test1="" data-test2="1061364-41" data-test3-original="41" data-test4-eu="41" data-test5-uk="7" data-test6-us="8" data-test-cm="26"></a> </div> ''' # Initialize BeautifulSoup with your HTML content soup = BeautifulSoup(html_content, "html.parser") # Find the target div with class "size" size_div = soup.find("div", class_="size") # Using `class_` is more readable than {"class": "size"} # Find the <a> tag inside the div (this is where the attribute lives) size_link = size_div.find("a", class_="selectSize") # Get the value of data-test5-uk uk_size = size_link.get("data-test5-uk") # Or do it all in one concise line if you prefer uk_size = soup.find("div", class_="size").find("a", class_="selectSize").get("data-test5-uk") print(uk_size) # Output: 7
Key tips here:
- Use
.get()to fetch attributes instead of direct bracket notation (likesize_link["data-test5-uk"])..get()will returnNoneif the attribute doesn't exist, avoiding aKeyError. - Remember that the
data-test5-ukattribute is attached to the<a>tag inside the<div>, so you need to traverse to that element first. - If you have multiple
.sizedivs on the page, usefind_all()and loop through them:all_size_divs = soup.find_all("div", class_="size") for div in all_size_divs: link = div.find("a", class_="selectSize") uk_size = link.get("data-test5-uk") if uk_size: print(f"Found UK size: {uk_size}")
内容的提问来源于stack exchange,提问作者Ogden
相关产品推荐
相关产品推荐

