File size: 8,355 Bytes
a74b879 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 | """
Mobile-Friendly Checker
Analyzes website mobile responsiveness and provides recommendations
"""
import requests
import re
from bs4 import BeautifulSoup
from typing import Dict, List
def check_mobile_friendly(url: str) -> Dict:
"""
Check if a website is mobile-friendly
Returns score and recommendations
"""
try:
headers = {
'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15'
}
response = requests.get(url, headers=headers, timeout=10)
html = response.text
soup = BeautifulSoup(html, 'html.parser')
score = 100
issues = []
recommendations = []
# Check viewport meta tag
viewport = soup.find('meta', attrs={'name': 'viewport'})
if not viewport:
score -= 30
issues.append({
'type': 'missing_viewport',
'severity': 'critical',
'message': 'لا يوجد viewport meta tag - الموقع غير متجاوب'
})
recommendations.append('أضف <meta name="viewport" content="width=device-width, initial-scale=1">')
else:
content = viewport.get('content', '')
if 'width=device-width' not in content:
score -= 15
issues.append({
'type': 'incorrect_viewport',
'severity': 'high',
'message': 'viewport غير صحيح'
})
# Check for responsive CSS
has_media_queries = False
for style in soup.find_all('style'):
if '@media' in style.string if style.string else '':
has_media_queries = True
break
for link in soup.find_all('link', rel='stylesheet'):
href = link.get('href', '')
if href:
try:
css_response = requests.get(href if href.startswith('http') else url + href, timeout=5)
if '@media' in css_response.text:
has_media_queries = True
break
except:
pass
if not has_media_queries:
score -= 20
issues.append({
'type': 'no_media_queries',
'severity': 'high',
'message': 'لا توجد media queries - التصميم غير متجاوب'
})
recommendations.append('استخدم CSS media queries للتصميم المتجاوب')
# Check font sizes
small_fonts = soup.find_all(string=re.compile(r'font-size:\s*[0-9]px'))
if len(small_fonts) > 5:
score -= 10
issues.append({
'type': 'small_fonts',
'severity': 'medium',
'message': 'خطوط صغيرة جداً على الموبايل'
})
recommendations.append('استخدم أحجام خطوط لا تقل عن 16px للنصوص الأساسية')
# Check for fixed width elements
fixed_width = soup.find_all(style=re.compile(r'width:\s*[0-9]{4,}px'))
if fixed_width:
score -= 15
issues.append({
'type': 'fixed_width',
'severity': 'high',
'message': f'عناصر بعرض ثابت ({len(fixed_width)} عنصر)'
})
recommendations.append('استخدم النسب المئوية بدلاً من البكسل الثابت')
# Check touch targets
buttons = soup.find_all(['button', 'a'])
small_buttons = 0
for btn in buttons:
style = btn.get('style', '')
if 'width' in style or 'height' in style:
# Check if too small (less than 44px)
if re.search(r'(width|height):\s*[1-3][0-9]px', style):
small_buttons += 1
if small_buttons > 3:
score -= 10
issues.append({
'type': 'small_touch_targets',
'severity': 'medium',
'message': f'أزرار صغيرة جداً ({small_buttons} زر)'
})
recommendations.append('اجعل الأزرار والروابط بحجم 44x44px على الأقل')
# Check for horizontal scrolling
if 'overflow-x' in html and 'scroll' in html:
score -= 10
issues.append({
'type': 'horizontal_scroll',
'severity': 'medium',
'message': 'قد يحتوي على تمرير أفقي'
})
status = 'ممتاز ✅' if score >= 90 else 'جيد ✓' if score >= 70 else 'يحتاج تحسين ⚠️' if score >= 50 else 'ضعيف ❌'
return {
'ok': True,
'score': max(0, score),
'status': status,
'issues': issues,
'recommendations': recommendations,
'details': {
'has_viewport': bool(viewport),
'has_media_queries': has_media_queries,
'small_fonts_count': len(small_fonts),
'fixed_width_count': len(fixed_width),
'small_buttons_count': small_buttons
}
}
except Exception as e:
return {
'ok': False,
'error': str(e),
'score': 0,
'status': 'فشل الفحص',
'issues': [],
'recommendations': []
}
def get_mobile_score_from_pagespeed(url: str) -> Dict:
"""
Get mobile score from Google PageSpeed Insights API
"""
try:
import os
api_key = os.getenv('GOOGLE_PAGESPEED_KEY')
if not api_key:
return check_mobile_friendly(url)
api_url = f'https://www.googleapis.com/pagespeedonline/v5/runPagespeed'
params = {
'url': url,
'key': api_key,
'strategy': 'mobile',
'category': 'performance'
}
response = requests.get(api_url, params=params, timeout=30)
data = response.json()
if 'lighthouseResult' not in data:
return check_mobile_friendly(url)
lighthouse = data['lighthouseResult']
categories = lighthouse.get('categories', {})
performance = categories.get('performance', {}).get('score', 0) * 100
audits = lighthouse.get('audits', {})
viewport_audit = audits.get('viewport', {})
font_size_audit = audits.get('font-size', {})
tap_targets_audit = audits.get('tap-targets', {})
issues = []
recommendations = []
score = int(performance)
if viewport_audit.get('score', 1) < 1:
issues.append({
'type': 'viewport',
'severity': 'critical',
'message': viewport_audit.get('title', 'مشكلة في viewport')
})
recommendations.append(viewport_audit.get('description', ''))
if font_size_audit.get('score', 1) < 1:
issues.append({
'type': 'font_size',
'severity': 'medium',
'message': font_size_audit.get('title', 'خطوط صغيرة')
})
recommendations.append(font_size_audit.get('description', ''))
if tap_targets_audit.get('score', 1) < 1:
issues.append({
'type': 'tap_targets',
'severity': 'medium',
'message': tap_targets_audit.get('title', 'أزرار صغيرة')
})
recommendations.append(tap_targets_audit.get('description', ''))
status = 'ممتاز ✅' if score >= 90 else 'جيد ✓' if score >= 70 else 'يحتاج تحسين ⚠️' if score >= 50 else 'ضعيف ❌'
return {
'ok': True,
'score': score,
'status': status,
'issues': issues,
'recommendations': [r for r in recommendations if r],
'source': 'pagespeed'
}
except Exception as e:
return check_mobile_friendly(url)
|