从静态XML文件提取产品名:限制前10条并支持单独调用
Solution to Get First 10 Product Names with Individual Access
Here's how you can modify your code to collect the first 10 product names and access each one via a named attribute like start_tag_5:
First, we'll adjust the function to collect results into a list, limit it to 10 items, then create a custom object to hold each result as an attribute.
# Define the static webpage file path static_webpage_1 = 'StaticStock/acoustic_guitar.html' class ProductNameContainer: pass def Find_static_webpage_product_name(): # Open and read the contents of the file (using with for proper file handling) with open(static_webpage_1, encoding="utf8") as file: read_xml_code = file.read() start_tag = '<title><![CDATA[' end_tag = ']]></title>' end_position = 0 product_names = [] # Collect up to 10 product names while len(product_names) < 10: starting_position = read_xml_code.find(start_tag, end_position) if starting_position == -1: # No more tags found break end_position = read_xml_code.find(end_tag, starting_position) if end_position == -1: # Mismatched tags, stop early break # Extract and store the product name product_name = read_xml_code[starting_position + len(start_tag) : end_position] product_names.append(product_name) # Update position to search for the next tag end_position += len(end_tag) # Create a container object to hold each product name as a named attribute name_container = ProductNameContainer() for index, name in enumerate(product_names, start=1): setattr(name_container, f'start_tag_{index}', name) return name_container # Call the function to retrieve the container of product names read_xml_code = Find_static_webpage_product_name() # Example: Print the 5th product name print(read_xml_code.start_tag_5) # Optional: Print all collected product names for i in range(1, len(read_xml_code.__dict__) + 1): print(getattr(read_xml_code, f'start_tag_{i}'))
Key Changes Explained:
- Improved file handling: Using
withensures the file is closed automatically after reading, avoiding resource leaks. - Result collection: We store product names in a list instead of printing immediately, stopping once we have 10 items or exhaust all results.
- Custom attribute access: The
ProductNameContainerclass andsetattr()let us create named attributes likestart_tag_1tostart_tag_10, matching your requested access pattern. - Returnable container: The function returns the container object, so you can access individual results anywhere after calling the function.
Notes:
- If there are fewer than 10 product names in the file, only the available ones will be added as attributes (e.g., if there are 7, you can access up to
start_tag_7). - Numbering starts at 1 to align with your example of
start_tag_5for the 5th result.
内容的提问来源于stack exchange,提问作者Tomble
相关产品推荐
相关产品推荐

