Từ một web url, hãy viết Python code để lấy các dòng CSS code liên quan đến: Background color, Text color, button color, font style. Đảm bảo lấy không thừa cũng không thiếu. Chương trình sẽ bao gồm 2 hàm: extract toàn bộ css với đầu vào url, và sau đó là extract css liên quan với đầu vào là all_css.
Assistant
Sure! Below is a Python program that accomplishes the task you've described. The program consists of two main functions:
extract_all_css(url): This function takes a URL as input, fetches the HTML content of the page, parses it to find all linked external CSS files and embedded <style> tags, retrieves their CSS content, and returns all CSS as a single string.
extract_relevant_css(all_css): This function takes the combined CSS string produced by extract_all_css and parses it to extract only the CSS rules related to background color, text color, button color, and font style. It ensures that only relevant CSS is included without any excess.
Required Libraries
Before running the code, make sure to install the necessary Python libraries:
bash
pip install requests beautifulsoup4 cssutils
Python Code
python
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import cssutils
def extract_all_css(url):
"""
Extracts all CSS from the given URL, including external and embedded styles.
Args:
url (str): The URL of the webpage to extract CSS from.
Returns:
str: A string containing all the CSS from the webpage.
"""
try:
response = requests.get(url)
response.raise_for_status()
except requests.RequestException as e:
print(f"Error fetching the URL: {e}")
return ""
soup = BeautifulSoup(response.text, 'html.parser')
all_css = ""
# Extract external CSS files
links = soup.find_all('link', rel='stylesheet')
for link in links:
href = link.get('href')
if href:
css_url = urljoin(url, href)
try:
css_response = requests.get(css_url)
css_response.raise_for_status()
all_css += css_response.text + "\n"
except requests.RequestException as e:
print(f"Error fetching CSS file {css_url}: {e}")
# Extract embedded CSS
style_tags = soup.find_all('style')
for style in style_tags:
if style.string:
all_css += style.string + "\n"
return all_css
def extract_relevant_css(all_css):
"""
Extracts CSS rules related to background color, text color, button color, and font style.
Args:
all_css (str): The combined CSS string.
Returns:
str: A string containing only the relevant CSS rules.
"""
relevant_properties = {
'background',
'background-color',
'color',
'font',
'font-family',
'font-size',
'font-style',
'font-weight',
'border',
'border-color',
'border-style',
'border-width',
}
# Initialize a new CSS stylesheet
relevant_css = cssutils.css.CSSStyleSheet()
parser = cssutils.CSSParser()
try:
stylesheet = parser.parseString(all_css)
except cssutils.CSSSyntaxError as e:
print(f"CSS Syntax Error: {e}")
return ""
for rule in stylesheet:
if rule.type == rule.STYLE_RULE:
# Check if any relevant property is in the rule
has_relevant = False
for property in rule.style:
prop_name = property.name.lower()
if prop_name in relevant_properties:
has_relevant = True
break
if has_relevant:
relevant_css.add(rule)
elif rule.type in [rule.MEDIA_RULE, rule.PAGE_RULE, rule.FONT_FACE_RULE, rule.KEYFRAMES_RULE]:
# Optionally handle other rule types if needed
pass
return relevant_css.cssText.decode('utf-8')
def main():
url = input("Enter the URL of the webpage: ").strip()
print("Extracting all CSS...")
all_css = extract_all_css(url)
if not all_css:
print("No CSS found.")
return
print("Extracting relevant CSS...")
relevant_css = extract_relevant_css(all_css)
if not relevant_css:
print("No relevant CSS properties found.")
return
# Optionally, save the relevant CSS to a file
output_file = "relevant_styles.css"
with open(output_file, "w", encoding="utf-8") as f:
f.write(relevant_css)
print(f"Relevant CSS has been saved to {output_file}")
if __name__ == "__main__":
main()
How It Works
Fetching the Webpage and CSS:
The extract_all_css function fetches the HTML content of the provided URL using the requests library.
It then uses BeautifulSoup to parse the HTML and find all <link> tags with rel="stylesheet" to identify external CSS files.
For each external CSS file, it constructs the absolute URL (handling relative paths) and fetches its content.
It also looks for embedded <style> tags within the HTML and appends their content.
All CSS content is concatenated into a single string all_css.
Parsing and Filtering Relevant CSS:
The extract_relevant_css function uses cssutils to parse the combined CSS string.
It defines a set of relevant CSS properties related to background color, text color, button color, and font styles.
It iterates over each CSS rule and checks if any of the declarations within the rule match the relevant properties.
If a rule contains any relevant property, it is added to a new stylesheet relevant_css.
Finally, the relevant CSS is returned as a string.
Execution Flow:
The main function orchestrates the process by prompting the user for a URL, extracting all CSS, filtering the relevant CSS, and then saving the result to a file named relevant_styles.css.
Example Usage
bash
$ python extract_css.py
Enter the URL of the webpage: https://www.example.com
Extracting all CSS...
Extracting relevant CSS...
Relevant CSS has been saved to relevant_styles.css
After running the program, you'll find a file named relevant_styles.css in the same directory, containing only the CSS rules related to background color, text color, button color, and font styles.
Notes
Handling Relative URLs: The urljoin function from urllib.parse ensures that relative URLs are correctly resolved based on the base URL of the page.
CSS Specificity and Inheritance: This script extracts CSS rules that explicitly define the relevant properties. It does not account for inherited styles or CSS specificity. Depending on your use case, you might need a more sophisticated approach to determine the effective styles of elements.
Error Handling: Basic error handling is included to manage network issues and CSS parsing errors. You can enhance this further based on your requirements.
Extensibility: You can easily extend the relevant_properties set to include more CSS properties as needed.
I hope this helps! Let me know if you have any questions or need further assistance.