To create a Python function that accepts HTML code as input, searches for a Steam store app ID, and returns the app ID if found (or 0 otherwise), we can use regular expressions (re module) to identify patterns in the text.
A Steam store app ID is typically a numeric value associated with a URL or data attribute in the HTML. For example:
- In URLs:
https://store.steampowered.com/app/123456/
- As part of data attributes:
data-appid="123456"
Here’s how we can implement this:
Code Implementation
import re
def find_steam_app_id(html_code):
"""
Searches for a Steam store app ID in the given HTML code.
Args:
html_code (str): The HTML content of a single page.
Returns:
int: The Steam app ID if found, otherwise 0.
"""
# Define a regex pattern to match Steam app IDs
# This pattern looks for digits following '/app/' or 'data-appid='
steam_app_id_pattern = r'(?:/app/|data-appid=["\'])(\d+)'
# Search for the pattern in the HTML code
match = re.search(steam_app_id_pattern, html_code)
# If a match is found, return the app ID as an integer
if match:
return int(match.group(1))
# If no match is found, return 0
return 0
Explanation of the Code
-
Regex Pattern:
(?:/app/|data-appid=["\']): Matches either /app/ or data-appid=" or data-appid='. The (?:...) syntax denotes a non-capturing group.
(\d+): Captures one or more digits (\d+) that follow the preceding pattern. This is the actual app ID we want to extract.
-
Regex Search:
re.search() scans the entire html_code string for the first occurrence of the pattern. If a match is found, it returns a match object; otherwise, it returns None.
-
Return Value:
- If a match is found,
match.group(1) extracts the captured digits (the app ID) and converts it to an integer before returning.
- If no match is found, the function returns
0.
Example Usage
# Example 1: HTML contains a Steam app ID
html_with_app_id = '''
<div>
<a href="https://store.steampowered.com/app/730/">Counter-Strike: Global Offensive</a>
<span data-appid="730"></span>
</div>
'''
print(find_steam_app_id(html_with_app_id)) # Output: 730
# Example 2: HTML does not contain a Steam app ID
html_without_app_id = '''
<div>
<p>Welcome to our website!</p>
</div>
'''
print(find_steam_app_id(html_without_app_id)) # Output: 0
Edge Cases Handled
- No App ID Present: If the HTML does not contain any Steam app ID, the function correctly returns
0.
- Multiple App IDs: The function extracts only the first app ID it encounters. If multiple app IDs are present, you may need to modify the function to return all matches.
- Malformed HTML: The function relies on regex, so it works even if the HTML is not perfectly structured, as long as the app ID follows the expected patterns.
Final Answer
The function find_steam_app_id(html_code) successfully identifies Steam app IDs in HTML code and returns the app ID or 0 if none is found.