# Combine all properties into a single regex pattern
pattern = '|'.join([item for sublist in relevant_properties.values() for item in sublist])
# Parse the CSS using tinycss2
stylesheet = tinycss2.parse_stylesheet(all_css)
relevant_css = []
for rule in stylesheet:
if rule.type == 'qualified-rule':
selector = tinycss2.serialize(rule.prelude)
declarations = tinycss2.parse_declaration_list(tinycss2.serialize(rule.content))
relevant_styles = []
for decl in declarations:
if decl.type == 'declaration':
property_name = decl.lower_name
property_value = tinycss2.serialize(decl.value)
if re.search(pattern, property_name, re.IGNORECASE) or \
re.search(pattern, f"{selector} {property_name}", re.IGNORECASE) or \
re.search(pattern, f"{property_name}: {property_value}", re.IGNORECASE):
relevant_styles.append(f"{property_name}: {property_value};")
if relevant_styles:
relevant_css.append(f"{selector} {{\n " + "\n ".join(relevant_styles) + "\n}")
return "\n\n".join(relevant_css)
Example usage
url = "https://ftu.edu.vn/"
all_css = extract_all_css(url)
relevant_css = extract_relevant_css(all_css)
print(relevant_css)
print(len(all_css))
print(len(relevant_css)) \n Đoạn code này nhằm từ 1 web url trích xuất được các dòng code liên quan đến background color, button color, text color và font style. Hiện tại với trang web url = "https://ftu.edu.vn/" đang thiếu thông tin về background color khiến cho việc phân tích sai. Hãy tối ưu lại code!
Để đảm bảo rằng các thông tin về background-color và các thuộc tính liên quan khác được trích xuất đầy đủ từ trang web, chúng ta cần tối ưu lại đoạn mã hiện tại bằng cách xử lý riêng biệt các inline styles và CSS từ các nguồn khác (như embedded styles và external stylesheets). Dưới đây là những bước tối ưu mà bạn có thể thực hiện:
Phân tách Inline Styles và CSS Khác:
Inline Styles thường được áp dụng trực tiếp trên các thẻ HTML và không có selector rõ ràng. Do đó, chúng ta cần xử lý riêng biệt để đảm bảo các thuộc tính như background-color được trích xuất chính xác.
Các embedded styles và external stylesheets có thể được xử lý như hiện tại, nhưng cần đảm bảo rằng các khai báo CSS được kết hợp và phân tích đúng cách.
Cải thiện Regex Pattern:
Đảm bảo rằng các pattern sử dụng để tìm kiếm các thuộc tính liên quan (background-color, button-color, text-color, font-style, v.v.) được xác định một cách chính xác để không bỏ sót bất kỳ thuộc tính nào.
Có thể thêm các pattern bổ sung để bao quát nhiều cách viết khác nhau của các thuộc tính CSS.
Xử lý Shorthand Properties:
Thuộc tính background có thể chứa nhiều thông tin như background-color, background-image, v.v. Do đó, cần tách riêng background-color từ các khai báo shorthand để đảm bảo không bị bỏ sót.
Dưới đây là đoạn mã đã được tối ưu dựa trên những điểm trên:
python
import requests
from bs4 import BeautifulSoup
import re
import cssutils
import logging
from urllib.parse import urljoin
import tinycss2
# Suppress cssutils warnings
cssutils.log.setLevel(logging.CRITICAL)
def extract_all_css(url):
# Fetch the webpage content
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Extract inline styles
inline_styles = [tag['style'] for tag in soup.find_all(attrs={'style': True})]
# Extract embedded styles
embedded_styles = ' '.join([style.string for style in soup.find_all('style') if style.string])
# Extract external stylesheet URLs
stylesheet_urls = [link['href'] for link in soup.find_all('link', rel='stylesheet') if 'href' in link.attrs]
# Fetch and concatenate external stylesheets
external_styles = ''
for stylesheet_url in stylesheet_urls:
absolute_url = urljoin(url, stylesheet_url)
try:
resp = requests.get(absolute_url)
resp.raise_for_status()
external_styles += resp.text + '\n'
except requests.RequestException:
print(f"Failed to fetch stylesheet: {absolute_url}")
return inline_styles, embedded_styles, external_styles
def extract_relevant_css(inline_styles, embedded_styles, external_styles):
relevant_properties = {
'background': [
r'^background(?:-color)?$',
r'^background-image$',
r'^background$',
],
'button': [
r'^button$',
r'^\.btn$',
r'^\[type=(\'|")(?:button|submit)\1\]$',
r'^\.button$',
r'^a\.',
r'^input\[type=(\'|")(?:button|submit)\1\]$',
r'^--.*?(?:btn|button)$',
r'^\.cta$',
r'^\.primary$',
r'^\.secondary$',
r'^\.action$',
],
'text': [
r'^color$',
r'^opacity$',
],
'font': [
r'^font(?:-family|-size|-weight|-style)?$',
r'^text-decoration$',
r'^text-transform$',
r'^line-height$',
r'^letter-spacing$',
],
'body': [
r'^body$',
r'^html$',
],
'variables': [
r'^--.*?(?:color|font|bg|background|button|text)$',
],
'other': [
r'^box-shadow$',
r'^(?:linear|radial)-gradient$',
r'^border$',
r'^outline$',
]
}
# Combine all properties into a single regex pattern
# Use word boundaries to ensure exact matches
pattern = '|'.join([f'({item})' for sublist in relevant_properties.values() for item in sublist])
pattern = re.compile(pattern, re.IGNORECASE)
relevant_css = []
# Function to extract relevant declarations from a list of declarations
def get_relevant_declarations(declarations):
relevant_styles = []
for decl in declarations:
if decl.type == 'declaration' and not decl.name.startswith('--'):
property_name = decl.lower_name
property_value = tinycss2.serialize(decl.value).strip()
if pattern.match(property_name):
relevant_styles.append(f"{property_name}: {property_value};")
return relevant_styles
# Process embedded and external styles
combined_styles = embedded_styles + '\n' + external_styles
stylesheet = tinycss2.parse_stylesheet(combined_styles, skip_comments=True, skip_whitespace=True)
for rule in stylesheet:
if rule.type == 'qualified-rule':
selector = tinycss2.serialize(rule.prelude).strip()
declarations = tinycss2.parse_declaration_list(rule.content, skip_comments=True, skip_whitespace=True)
relevant_styles = get_relevant_declarations(declarations)
# If 'background' shorthand is used, attempt to extract 'background-color'
if any(decl.lower_name == 'background' for decl in declarations):
for decl in declarations:
if decl.lower_name == 'background':
bg_value = tinycss2.serialize(decl.value).strip()
# Simple regex to extract hex colors, rgb/rgba, hsl/hsla, or color names
color_match = re.search(r'(#[0-9a-fA-F]{3,8}|rgba?\([^\)]+\)|hsla?\([^\)]+\)|\b[a-zA-Z]+\b)', bg_value)
if color_match:
background_color = color_match.group(1)
relevant_styles.append(f"background-color: {background_color};")
if relevant_styles:
relevant_css.append(f"{selector} {{\n " + "\n ".join(relevant_styles) + "\n}")
# Process inline styles
for style_text in inline_styles:
declarations = tinycss2.parse_declaration_list(style_text, skip_comments=True, skip_whitespace=True)
relevant_styles = get_relevant_declarations(declarations)
# Handle 'background' shorthand in inline styles
for decl in declarations:
if decl.type == 'declaration' and decl.lower_name == 'background':
bg_value = tinycss2.serialize(decl.value).strip()
color_match = re.search(r'(#[0-9a-fA-F]{3,8}|rgba?\([^\)]+\)|hsla?\([^\)]+\)|\b[a-zA-Z]+\b)', bg_value)
if color_match:
background_color = color_match.group(1)
relevant_styles.append(f"background-color: {background_color};")
if relevant_styles:
# Sử dụng một selector đặc biệt để chỉ các inline styles
relevant_css.append(f"/* inline style */ {{\n " + "\n ".join(relevant_styles) + "\n}")
return "\n\n".join(relevant_css)
# Example usage
if __name__ == "__main__":
url = "https://ftu.edu.vn/"
inline_styles, embedded_styles, external_styles = extract_all_css(url)
relevant_css = extract_relevant_css(inline_styles, embedded_styles, external_styles)
print("Relevant CSS:\n")
print(relevant_css)
print("\nLength of all CSS:", len(embedded_styles) + len(external_styles) + sum(len(s) for s in inline_styles))
print("Length of relevant CSS:", len(relevant_css))
Những điểm cải tiến chính:
Phân tách Rõ Ràng Các Nguồn CSS:
Inline Styles: Được lưu trữ dưới dạng danh sách và xử lý riêng biệt để đảm bảo rằng các thuộc tính như background-color không bị bỏ sót.
Embedded và External Styles: Được kết hợp thành một chuỗi duy nhất để tiện cho việc phân tích.
Cải Thiện Regex Patterns:
Sử dụng ^ và $ trong các pattern để đảm bảo rằng các thuộc tính được khớp chính xác.
Kết hợp các pattern thành một biểu thức chính quy duy nhất với các dấu ngoặc để đảm bảo không bị nhầm lẫn giữa các nhóm.
Xử Lý Shorthand Properties:
Khi gặp thuộc tính background, cố gắng tách background-color từ giá trị của nó bằng cách sử dụng regex để tìm kiếm các ký tự màu hợp lệ (như hex, rgb, rgba, hsl, hsla hoặc tên màu).
Xử Lý Inline Styles Rõ Ràng:
Thêm các inline styles vào relevant_css với một selector đặc biệt (/* inline style */) để phân biệt chúng với các khai báo CSS từ các nguồn khác.
Kiểm Tra và Xử Lý Lỗi Khi Fetch CSS:
Sử dụng resp.raise_for_status() để đảm bảo rằng các stylesheet được tải thành công. Nếu không, sẽ thông báo lỗi cụ thể hơn.
Kết Quả
Sau khi chạy đoạn mã trên với URL https://ftu.edu.vn/, bạn sẽ nhận được các khai báo CSS liên quan đến background-color, button-color, text-color, và font-style một cách đầy đủ hơn. Điều này sẽ cải thiện đáng kể việc phân tích và xử lý các thông tin về giao diện của trang web.
Nếu bạn vẫn gặp phải vấn đề về việc thiếu thông tin background-color, hãy kiểm tra lại nguồn CSS của trang web để đảm bảo rằng các thuộc tính này không được áp dụng thông qua JavaScript hoặc các phương thức động khác mà không thể được trích xuất thông qua yêu cầu HTTP thông thường.