File size: 13,170 Bytes
a9002e6 1f34280 b3b712b a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 1f34280 a9002e6 eef2a73 |
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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
import random
import asyncio
from playwright.async_api import async_playwright
import random
async def fetch_html(url, max_retries=5, min_delay=1, max_delay=3, headless=True, timeout=30000):
"""
Fetch HTML using Playwright with retries and anti-bot measures.
Args:
url (str): The URL to fetch
max_retries (int): Maximum number of retry attempts
min_delay (float): Minimum delay between retries in seconds
max_delay (float): Maximum delay between retries in seconds
headless (bool): Whether to run browser in headless mode
timeout (int): Page load timeout in milliseconds
Returns:
str or None: HTML content as string or None if failed
"""
for attempt in range(1, max_retries + 1):
print(f"[INFO] Fetching {url} (Attempt {attempt}/{max_retries})")
try:
async with async_playwright() as p:
# Launch browser with realistic settings
browser = await p.chromium.launch(
headless=headless,
args=[
'--no-sandbox',
'--disable-blink-features=AutomationControlled',
'--disable-dev-shm-usage',
'--disable-web-security',
'--disable-features=VizDisplayCompositor',
'--user-agent=Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
]
)
# Create context with realistic settings
context = await browser.new_context(
user_agent=(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
),
locale='ar-SA',
timezone_id='Asia/Riyadh',
viewport={'width': 1920, 'height': 1080},
extra_http_headers={
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "ar,en-US;q=0.9,en;q=0.8",
"Accept-Encoding": "gzip, deflate, br",
"DNT": "1",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
"Referer": "https://shamela.ws/",
}
)
# Create page and set additional stealth measures
page = await context.new_page()
# Hide webdriver traces
await page.add_init_script("""
Object.defineProperty(navigator, 'webdriver', {
get: () => undefined,
});
window.chrome = {
runtime: {},
};
Object.defineProperty(navigator, 'plugins', {
get: () => [1, 2, 3, 4, 5],
});
Object.defineProperty(navigator, 'languages', {
get: () => ['ar', 'en-US', 'en'],
});
""")
# Navigate to the page
response = await page.goto(url, wait_until='domcontentloaded', timeout=timeout)
if response and response.status == 200:
# Wait a bit for any dynamic content
await page.wait_for_timeout(random.randint(1000, 3000))
# Optional: Wait for specific elements if needed
# await page.wait_for_selector('body', timeout=5000)
# Get the HTML content
html = await page.content()
if len(html.strip()) > 500:
# ✅ Got valid HTML
preview = html[:300].replace("\n", " ")
print(f"[OK] {url} (Attempt {attempt}) | Preview: {preview[:150]}...")
await browser.close()
return html
else:
print(f"[WARN] Short HTML content ({len(html)} chars) on attempt {attempt}")
else:
status = response.status if response else "No response"
print(f"[WARN] Status {status} on attempt {attempt}")
await browser.close()
except Exception as e:
print(f"[ERROR] Attempt {attempt}: {e}")
# Wait before retrying
if attempt < max_retries:
wait_time = random.uniform(min_delay, max_delay)
print(f"[INFO] Waiting {wait_time:.1f} seconds before retry...")
await asyncio.sleep(wait_time)
print(f"[FAIL] Could not fetch {url} after {max_retries} attempts.")
return None
async def fetch_html_with_js_execution(url, max_retries=5, min_delay=1, max_delay=3, headless=True, timeout=30000, wait_for_js=True):
"""
Enhanced version that can execute JavaScript and wait for dynamic content.
Args:
url (str): The URL to fetch
max_retries (int): Maximum number of retry attempts
min_delay (float): Minimum delay between retries in seconds
max_delay (float): Maximum delay between retries in seconds
headless (bool): Whether to run browser in headless mode
timeout (int): Page load timeout in milliseconds
wait_for_js (bool): Whether to wait for JavaScript to execute
Returns:
str or None: HTML content as string or None if failed
"""
for attempt in range(1, max_retries + 1):
print(f"[INFO] Fetching {url} with JS execution (Attempt {attempt}/{max_retries})")
try:
async with async_playwright() as p:
browser = await p.chromium.launch(
headless=headless,
args=[
'--no-sandbox',
'--disable-blink-features=AutomationControlled',
'--disable-dev-shm-usage',
'--disable-web-security',
'--disable-features=VizDisplayCompositor'
]
)
context = await browser.new_context(
user_agent=(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/120.0.0.0 Safari/537.36"
),
locale='ar-SA',
timezone_id='Asia/Riyadh',
viewport={'width': 1920, 'height': 1080},
java_script_enabled=True
)
page = await context.new_page()
# Navigate and wait for network to be idle
response = await page.goto(url, wait_until='networkidle', timeout=timeout)
if response and response.status == 200:
if wait_for_js:
# Wait for common dynamic content indicators
try:
await page.wait_for_load_state('networkidle', timeout=10000)
except:
pass # Continue even if network doesn't idle
# Additional wait for any remaining dynamic content
await page.wait_for_timeout(random.randint(2000, 5000))
html = await page.content()
if len(html.strip()) > 500:
preview = html[:300].replace("\n", " ")
print(f"[OK] {url} (Attempt {attempt}) | Preview: {preview[:150]}...")
await browser.close()
return html
else:
print(f"[WARN] Short HTML content ({len(html)} chars) on attempt {attempt}")
else:
status = response.status if response else "No response"
print(f"[WARN] Status {status} on attempt {attempt}")
await browser.close()
except Exception as e:
print(f"[ERROR] Attempt {attempt}: {e}")
if attempt < max_retries:
wait_time = random.uniform(min_delay, max_delay)
print(f"[INFO] Waiting {wait_time:.1f} seconds before retry...")
await asyncio.sleep(wait_time)
print(f"[FAIL] Could not fetch {url} after {max_retries} attempts.")
return None
async def fetch_html_with_browser(url, browser_type='chromium', max_retries=5, min_delay=1, max_delay=3, headless=True, timeout=30000):
"""
Fetch HTML using different browser types (chromium, firefox, webkit).
Args:
url (str): The URL to fetch
browser_type (str): Browser type ('chromium', 'firefox', 'webkit')
max_retries (int): Maximum number of retry attempts
min_delay (float): Minimum delay between retries in seconds
max_delay (float): Maximum delay between retries in seconds
headless (bool): Whether to run browser in headless mode
timeout (int): Page load timeout in milliseconds
Returns:
str or None: HTML content as string or None if failed
"""
for attempt in range(1, max_retries + 1):
print(f"[INFO] Fetching {url} with {browser_type} (Attempt {attempt}/{max_retries})")
try:
async with async_playwright() as p:
# Get the appropriate browser
if browser_type.lower() == 'firefox':
browser = await p.firefox.launch(headless=headless)
user_agent = "Mozilla/5.0 (X11; Linux x86_64; rv:120.0) Gecko/20100101 Firefox/120.0"
elif browser_type.lower() == 'webkit':
browser = await p.webkit.launch(headless=headless)
user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15"
else: # default to chromium
browser = await p.chromium.launch(
headless=headless,
args=[
'--no-sandbox',
'--disable-blink-features=AutomationControlled',
'--disable-dev-shm-usage',
'--disable-web-security',
'--disable-features=VizDisplayCompositor'
]
)
user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
context = await browser.new_context(
user_agent=user_agent,
locale='ar-SA',
timezone_id='Asia/Riyadh',
viewport={'width': 1920, 'height': 1080}
)
page = await context.new_page()
# Navigate to the page
response = await page.goto(url, wait_until='domcontentloaded', timeout=timeout)
if response and response.status == 200:
# Wait a bit for any dynamic content
await page.wait_for_timeout(random.randint(1000, 3000))
html = await page.content()
if len(html.strip()) > 500:
preview = html[:300].replace("\n", " ")
print(f"[OK] {url} with {browser_type} (Attempt {attempt}) | Preview: {preview[:150]}...")
await browser.close()
return html
else:
print(f"[WARN] Short HTML content ({len(html)} chars) on attempt {attempt}")
else:
status = response.status if response else "No response"
print(f"[WARN] Status {status} on attempt {attempt}")
await browser.close()
except Exception as e:
print(f"[ERROR] Attempt {attempt} with {browser_type}: {e}")
if attempt < max_retries:
wait_time = random.uniform(min_delay, max_delay)
print(f"[INFO] Waiting {wait_time:.1f} seconds before retry...")
await asyncio.sleep(wait_time)
print(f"[FAIL] Could not fetch {url} with {browser_type} after {max_retries} attempts.")
return None |