File size: 19,112 Bytes
0093c99
9704817
0093c99
 
9704817
0093c99
42a8301
0093c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f2a181
0093c99
3f2a181
0093c99
3f2a181
0093c99
 
 
 
 
 
3f2a181
0093c99
 
 
 
 
3f2a181
 
0093c99
3f2a181
0093c99
 
 
 
3f2a181
0093c99
3f2a181
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0093c99
 
 
3f2a181
0093c99
 
 
 
 
 
 
 
 
 
 
3f2a181
 
0093c99
 
 
 
 
 
 
 
3f2a181
 
 
 
 
0093c99
 
 
3f2a181
 
0093c99
3f2a181
0093c99
3f2a181
0093c99
 
 
3f2a181
0093c99
 
 
 
3f2a181
9704817
3f2a181
 
0093c99
3f2a181
 
 
0093c99
 
3f2a181
 
0093c99
3f2a181
0093c99
3f2a181
0093c99
 
 
 
 
 
 
 
112c277
 
 
 
0093c99
 
3f2a181
0093c99
3f2a181
0093c99
 
 
 
 
 
 
3f2a181
0093c99
 
 
 
3f2a181
 
0093c99
 
 
 
 
 
 
 
3f2a181
0093c99
 
3f2a181
0093c99
 
3f2a181
 
9704817
3f2a181
 
 
0093c99
 
 
 
3f2a181
0093c99
3f2a181
0093c99
3f2a181
0093c99
 
3f2a181
0093c99
 
 
 
 
3f2a181
0093c99
 
3f2a181
0093c99
3f2a181
0093c99
 
 
3f2a181
0093c99
3f2a181
 
 
0093c99
3f2a181
 
 
 
0093c99
 
3f2a181
 
 
9704817
3f2a181
 
 
 
0093c99
 
3f2a181
0093c99
 
 
 
 
 
 
3f2a181
 
 
 
0093c99
 
 
 
 
 
9704817
04f322e
9704817
 
3f2a181
9704817
 
0093c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f2a181
 
 
 
 
 
0093c99
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42a8301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0093c99
 
 
 
 
3f2a181
 
 
 
 
0093c99
 
 
9704817
 
3f2a181
9704817
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f2a181
9704817
3f2a181
9704817
3f2a181
 
 
 
9704817
 
 
 
 
 
 
 
 
 
3f2a181
9704817
 
 
 
0093c99
 
 
 
 
04f322e
0093c99
 
 
04f322e
 
0093c99
 
04f322e
 
 
 
 
 
 
 
0093c99
 
04f322e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0093c99
42a8301
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0093c99
42a8301
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
import asyncio
import json
from typing import Dict, Optional, List
from playwright.async_api import async_playwright
import pandas as pd

from constant import COUNTRY_CODES, REVERSE_COUNTRY_CODES
class PassportIndexVisaScraper:
    def __init__(self, debug: bool = True):
        """
        Initialize the Passport Index visa scraper using Playwright
        
        Args:
            debug: Enable debug output
        """
        self.base_url = "https://www.passportindex.org/travel-visa-checker/"
        self.api_url = "https://www.passportindex.org/core/visachecker.php"
        self.debug = debug
        self.browser = None
        self.context = None
        self.page = None
        
    async def __aenter__(self):
        """Initialize browser with stealth mode"""
        self.playwright = await async_playwright().start()
        
        # Launch browser with stealth settings
        self.browser = await self.playwright.chromium.launch(
            headless=False,  # Using headless mode
            args=[
                '--disable-blink-features=AutomationControlled',
                '--disable-dev-shm-usage',
                '--no-sandbox',
                '--disable-setuid-sandbox',
                '--disable-web-security',
                '--disable-features=IsolateOrigins,site-per-process'
            ]
        )
        
        # Create context with realistic settings
        self.context = await self.browser.new_context(
            viewport={'width': 1920, 'height': 1080},
            user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36',
            locale='en-US',
            timezone_id='America/New_York'
        )
        
        self.page = await self.context.new_page()

        # Add stealth JavaScript to avoid detection
        await self.page.add_init_script("""
            // Override the navigator.webdriver property
            Object.defineProperty(navigator, 'webdriver', {
                get: () => undefined
            });

            // Override chrome property
            window.chrome = {
                runtime: {}
            };

            // Override permissions
            const originalQuery = window.navigator.permissions.query;
            window.navigator.permissions.query = (parameters) => (
                parameters.name === 'notifications' ?
                    Promise.resolve({ state: Notification.permission }) :
                    originalQuery(parameters)
            );
        """)
        
        if self.debug:
            print("πŸš€ Browser initialized with stealth mode")
        
        return self
    
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        """Clean up browser resources"""
        if self.page:
            await self.page.close()
        if self.context:
            await self.context.close()
        if self.browser:
            await self.browser.close()
        if self.playwright:
            await self.playwright.stop()
        
        if self.debug:
            print("πŸ”’ Browser closed")
    
    async def initialize_session(self) -> bool:
        """
        Navigate to the website and wait for it to load properly
        """
        try:
            if self.debug:
                print("πŸ“± Initializing session...")
            
            # Navigate to the page
            try:
                response = await self.page.goto(
                    self.base_url,
                    wait_until='domcontentloaded',
                    timeout=30000
                )
                await self.page.wait_for_timeout(3000)
                
                # Get the cl value from the page
                cl_value = await self.page.evaluate("""
                    () => {
                        const clInput = document.querySelector('#cl');
                        return clInput ? clInput.value : 'bc2140a2d83928ce1112d01e610bad89';
                    }
                """)
                
                if self.debug:
                    print(f"βœ… Page loaded, session ID: {cl_value}")
                    
                return True
                
            except Exception as e:
                if self.debug:
                    print(f"⚠️ Page load issue: {e}, continuing anyway...")
                return True
                
        except Exception as e:
            print(f"❌ Error initializing session: {e}")
            return False
    
    async def check_visa_requirement_browser(self, passport_country: str, destination_country: str) -> Optional[Dict]:
        """
        Check visa requirements using browser automation
        
        Args:
            passport_country: Two-letter country code for passport
            destination_country: Two-letter country code for destination
        
        Returns:
            Dictionary with visa information or None if failed
        """
        if destination_country.lower() == passport_country.lower():
            return {
                "text":  "Same country"
            }
        try:
            if self.debug:
                print(f"🌐 Checking {passport_country.upper()} β†’ {destination_country.upper()}")
            
            # Get the current session ID from the page
            cl_value = await self.page.evaluate("""
                () => {
                    const clInput = document.querySelector('#cl');
                    return clInput ? clInput.value : 'bc2140a2d83928ce1112d01e610bad89';
                }
            """)
            
            # Make the API request through the browser with proper argument passing
            result = await self.page.evaluate("""
                async (args) => {
                    const [passport, destination, sessionId] = args;
                    const formData = new URLSearchParams();
                    formData.append('d', destination);
                    formData.append('s', passport);
                    formData.append('cl', sessionId);
                    
                    try {
                        const response = await fetch('https://www.passportindex.org/core/visachecker.php', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                                'X-Requested-With': 'XMLHttpRequest',
                                'Accept': 'application/json, text/javascript, */*; q=0.01'
                            },
                            body: formData.toString(),
                            credentials: 'include'
                        });
                        
                        if (!response.ok) {
                            throw new Error(`HTTP ${response.status}`);
                        }
                        
                        const data = await response.json();
                        return data;
                    } catch (error) {
                        return { error: error.message };
                    }
                }
            """, [passport_country.lower(), destination_country.lower(), cl_value])
            
            if result and 'error' not in result:
                if self.debug:
                    print(f"βœ… Got result: {result}")
                return result
            elif result and 'error' in result:
                print(f"❌ API Error: {result['error']}")
                return None
            else:
                return None
                
        except Exception as e:
            print(f"❌ Error checking visa requirement: {e}")
            return None
    
    async def check_visa_interactive(self, passport_country: str, destination_country: str) -> Optional[Dict]:
        """
        Alternative method: Use the interactive UI to check visa requirements
        """
        try:
            if self.debug:
                print(f"πŸ–±οΈ Using interactive method for {passport_country.upper()} β†’ {destination_country.upper()}")
            
            # Click on the passport selector
            await self.page.click('.vch-select-pass')
            await self.page.wait_for_timeout(500)
            
            # Find and click the country in the list
            passport_selector = f'.vch-passports .s-div[data-ccode="{passport_country.lower()}"]'
            await self.page.wait_for_selector(passport_selector, timeout=5000)
            await self.page.click(passport_selector)
            await self.page.wait_for_timeout(500)
            
            # Click on the destination selector
            await self.page.click('.vch-select-des')
            await self.page.wait_for_timeout(500)
            
            # Find and click the destination country
            dest_selector = f'.vch-destinations .s-div[data-ccode="{destination_country.lower()}"]'
            await self.page.wait_for_selector(dest_selector, timeout=5000)
            await self.page.click(dest_selector)
            await self.page.wait_for_timeout(1000)
            
            # Get the result from the page
            result = await self.page.evaluate("""
                () => {
                    const resultElement = document.querySelector('.vch-result');
                    if (resultElement) {
                        const text = resultElement.querySelector('.text');
                        const days = resultElement.querySelector('.days');
                        return {
                            text: text ? text.textContent : '',
                            days: days ? days.textContent : '',
                            pass: '""" + passport_country.lower() + """',
                            dest: '""" + destination_country.upper() + """'
                        };
                    }
                    return null;
                }
            """)
            
            return result
            
        except Exception as e:
            if self.debug:
                print(f"❌ Interactive method failed: {e}")
            return None
    
    async def check_multiple_destinations(self, passport_country: str, destinations: List[str], delay: float = 2.0) -> Dict:
        """
        Check visa requirements for multiple destinations
        
        Args:
            passport_country: Two-letter country code for passport
            destinations: List of two-letter country codes for destinations
            delay: Delay between requests in seconds
        
        Returns:
            Dictionary mapping destination codes to visa information
        """
        results = {}
        
        for i, dest in enumerate(destinations, 1):
            print(f"\n[{i}/{len(destinations)}] Checking {passport_country.upper()} β†’ {dest.upper()}...")
            
            # Try API method first
            result = await self.check_visa_requirement_browser(passport_country, dest)
            
            # If API fails, try interactive method
            if not result:
                result = await self.check_visa_interactive(passport_country, dest)
            
            if result:
                results[dest] = result
                text = result.get('text', 'No text available')
                print(f"  βœ… Result: {text}")
            else:
                results[dest] = None
                print(f"  ❌ Failed to get result")
            
            # Rate limiting
            if i < len(destinations):
                print(f"  ⏳ Waiting {delay} seconds...")
                await asyncio.sleep(delay)
        
        return results
    async def check_multiple_source(self, passport_countries: List[str], destination: str, delay: float = 2.0) -> Dict:
        """
        Check visa requirements for multiple passport countries to a single destination.
        
        Args:
            passport_countries: List of two-letter country codes for passports.
            destination: Two-letter country code for the destination.
            delay: Delay between requests in seconds.
            
        Returns:
            Dictionary mapping passport country codes to visa information.
        """
        results = {}
        
        for i, passport in enumerate(passport_countries, 1):
            print(f"\n[{i}/{len(passport_countries)}] Checking {passport.upper()} β†’ {destination.upper()}...")
            
            # Try API method first
            result = await self.check_visa_requirement_browser(passport, destination)
            
            # If API fails, try interactive method
            if not result:
                result = await self.check_visa_interactive(passport, destination)
            
            if result:
                results[passport] = result
                text = result.get('text', 'No text available')
                print(f"  βœ… Result: {text}")
            else:
                results[passport] = None
                print(f"  ❌ Failed to get result")
            
            # Rate limiting to avoid blocking
            if i < len(passport_countries):
                print(f"  ⏳ Waiting {delay} seconds...")
                await asyncio.sleep(delay)
        
        return results
    def format_result(self, result: Dict) -> str:
        """Format a single result for display"""
        if not result:
            return "No information available"
        
        text = result.get('text', 'N/A')
        dest = result.get('dest', 'N/A')
        passport = result.get('pass', 'N/A')
        
        return f"{passport.upper()} β†’ {dest.upper()}: {text}"


async def main():
    """Main function to demonstrate usage"""
    print("="*60)
    print(" Passport Index Visa Checker (Playwright)")
    print("="*60)
    
    async with PassportIndexVisaScraper(debug=True) as scraper:
        # Initialize session
        if not await scraper.initialize_session():
            print("❌ Failed to initialize session")
            return
        
        print("\n" + "="*60)
        print(" Testing visa requirements...")
        print("="*60)
        
        # Test single visa requirement
        print("\nπŸ“ Single visa check: US β†’ GB")
        print("-" * 40)
        result = await scraper.check_visa_requirement_browser('us', 'gb')
        if result:
            print(f"Result: {scraper.format_result(result)}")
        else:
            print("Trying interactive method...")
            result = await scraper.check_visa_interactive('us', 'gb')
            if result:
                print(f"Result: {scraper.format_result(result)}")
        
        # Test multiple destinations
        print("\nπŸ“ Multiple destinations for US passport:")
        print("-" * 40)
        destinations = ['ca', 'mx', 'jp', 'au']  # Canada, Mexico, Japan, Australia
        results = await scraper.check_multiple_destinations('us', destinations, delay=2.0)
        
        print("\nπŸ“Š Summary:")
        for dest, result in results.items():
            if result:
                print(f"  βœ… {scraper.format_result(result)}")
            else:
                print(f"  ❌ US β†’ {dest.upper()}: Failed")

async def indo():
    print("="*60)
    print(" Passport Index Visa Checker (Playwright)")
    print("="*60)
    
    async with PassportIndexVisaScraper(debug=True) as scraper:
        l = []
        if not await scraper.initialize_session():
            print("❌ Failed to initialize session")
            return
        destinations = list(COUNTRY_CODES.values())
        results = await scraper.check_multiple_destinations('id', destinations, delay=2.0)
        for dest, result in results.items():
            if result:
                dic = {}
                dic['text'] = result.get('text', 'N/A')
                dic['days'] = result.get('days', 'N/A')
                dic['pass'] = result.get('pass', 'N/A')
                dic['dest'] = REVERSE_COUNTRY_CODES[dest]
                dic['source'] = 'Indonesia'
                l.append(dic)
                print(f"ID -> {dest.upper()}: {result.get('text', 'N/A')}")
            else:
                print(f"  ❌ US β†’ {dest.upper()}: Failed")
        results = await scraper.check_multiple_source(destinations, 'id', delay=2.0)
        for passport, result in results.items():
            if result:
                dic = {}
                dic['text'] = result.get('text', 'N/A')
                dic['days'] = result.get('days', 'N/A')
                dic['pass'] = result.get('pass', 'N/A')
                dic['dest'] = REVERSE_COUNTRY_CODES['id']
                dic['source'] = REVERSE_COUNTRY_CODES[passport]
                l.append(dic)
                print(f"{passport.upper()} -> ID: {result.get('text', 'N/A')}")
            else:
                print(f"  ❌ {passport.upper()} β†’ ID: Failed")

        # save to csv
        df = pd.DataFrame(l)
        df.to_csv('visa_avaibility_playwright.csv', index=False)




async def asean():
    print("="*60)
    print(" Passport Index Visa Checker (Playwright)")
    print("="*60)
    
    async with PassportIndexVisaScraper(debug=True) as scraper:
        l = []
        if not await scraper.initialize_session():
            print("❌ Failed to initialize session")
            return
        mains = ['kh', 'th', 'vn', 'la', 'mm', 'tl', 'ph', 'bn', 'my']
        destinations = list(COUNTRY_CODES.values())
        for main in mains:
            results = await scraper.check_multiple_destinations(main, destinations, delay=2.0)
            for dest, result in results.items():
                if result:
                    dic = {}
                    dic['text'] = result.get('text', 'N/A')
                    dic['days'] = result.get('days', 'N/A')
                    dic['pass'] = result.get('pass', 'N/A')
                    dic['dest'] = REVERSE_COUNTRY_CODES[dest]
                    dic['source'] = REVERSE_COUNTRY_CODES[main]
                    l.append(dic)
                    print(f"{main.upper()} -> {dest.upper()}: {result.get('text', 'N/A')}")
                else:
                    print(f"  ❌ {main.upper()} β†’ {dest.upper()}: Failed")
            results = await scraper.check_multiple_source(destinations, main, delay=2.0)
            for passport, result in results.items():
                if result:
                    dic = {}
                    dic['text'] = result.get('text', 'N/A')
                    dic['days'] = result.get('days', 'N/A')
                    dic['pass'] = result.get('pass', 'N/A')
                    dic['dest'] = REVERSE_COUNTRY_CODES[main]
                    dic['source'] = REVERSE_COUNTRY_CODES[passport]
                    l.append(dic)
                    print(f"{passport.upper()} -> {main.upper()}: {result.get('text', 'N/A')}")
                else:
                    print(f"  ❌ {passport.upper()} β†’ {main.upper()}: Failed")

        # save to csv
        df = pd.DataFrame(l)
        df.to_csv('asean_visa_avaibility_playwright.csv', index=False)

if __name__ == "__main__":
    asyncio.run(asean())