File size: 8,079 Bytes
94d93ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
from pathlib import Path
import time
import json

# Setup
output_dir = Path("arlo_pro3_rag/kb_articles")
output_dir.mkdir(parents=True, exist_ok=True)

# URLs to download
urls = [
    "https://kb.arlo.com/en_US/290",
    "https://kb.arlo.com/en_US/000062284",
    "https://kb.arlo.com/en_US/000062798",
    "https://kb.arlo.com/en_US/1202753",
    "https://kb.arlo.com/en_US/000062797",
    "https://kb.arlo.com/en_US/1273",
    "https://kb.arlo.com/en_US/000062777",
    "https://kb.arlo.com/en_US/3003",
    "https://kb.arlo.com/en_US/000062119",
    "https://kb.arlo.com/en_US/000062929",
    "https://kb.arlo.com/en_US/000062322",
    "https://kb.arlo.com/en_US/000062285",
    "https://kb.arlo.com/en_US/000062659",
    "https://kb.arlo.com/en_US/000062880",
    "https://kb.arlo.com/en_US/000062757",
    "https://kb.arlo.com/en_US/000062696",
    "https://kb.arlo.com/en_US/000062872"
]

# Configure Chrome options with more stability settings
chrome_options = Options()
chrome_options.add_argument("--headless=new")  # Updated headless mode
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--disable-software-rasterizer")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-logging")
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--window-size=1920,1080")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36")
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])

# Initialize driver with automatic ChromeDriver management
print("Initializing Chrome WebDriver...")
try:
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    driver.set_page_load_timeout(30)
    print("✓ WebDriver initialized successfully\n")
except Exception as e:
    print(f"✗ Failed to initialize WebDriver: {e}")
    print("\nTry running without headless mode for debugging.")
    exit(1)

results = []
failed_urls = []

for i, url in enumerate(urls, 1):
    clean_url = url.split('?')[0]
    article_id = clean_url.split('/')[-1]
    
    print(f"[{i}/{len(urls)}] Downloading article {article_id}...")
    
    max_retries = 2
    retry_count = 0
    success = False
    
    while retry_count < max_retries and not success:
        try:
            if retry_count > 0:
                print(f"  Retry {retry_count}/{max_retries-1}...")
            
            driver.get(clean_url)
            time.sleep(4)  # Increased wait time
            
            # Wait for main content to load with multiple selectors
            try:
                WebDriverWait(driver, 15).until(
                    EC.presence_of_element_located((By.TAG_NAME, "article"))
                )
            except:
                # Try alternative selector if article tag not found
                WebDriverWait(driver, 15).until(
                    EC.presence_of_element_located((By.CSS_SELECTOR, ".article-content, .kb-article, main"))
                )
            
            # Get page title
            try:
                title = driver.find_element(By.TAG_NAME, "h1").text
            except:
                try:
                    title = driver.title
                except:
                    title = f"Article {article_id}"
            
            # Get main content
            page_source = driver.page_source
            
            # Save HTML
            filename = f"article_{article_id}.html"
            filepath = output_dir / filename
            
            with open(filepath, 'w', encoding='utf-8') as f:
                f.write(page_source)
            
            # Extract main text content with multiple strategies
            article_text = None
            try:
                article_element = driver.find_element(By.TAG_NAME, "article")
                article_text = article_element.text
            except:
                try:
                    # Try alternative selectors
                    for selector in [".article-content", ".kb-article", "main", "body"]:
                        try:
                            element = driver.find_element(By.CSS_SELECTOR, selector)
                            article_text = element.text
                            if article_text and len(article_text) > 100:
                                break
                        except:
                            continue
                except:
                    pass
            
            if article_text and len(article_text) > 50:
                # Save text version
                text_filename = f"article_{article_id}.txt"
                text_filepath = output_dir / text_filename
                
                with open(text_filepath, 'w', encoding='utf-8') as f:
                    f.write(f"Title: {title}\n")
                    f.write(f"URL: {clean_url}\n")
                    f.write(f"{'='*80}\n\n")
                    f.write(article_text)
                
                results.append({
                    'id': article_id,
                    'title': title,
                    'url': clean_url,
                    'status': 'success',
                    'html_file': filename,
                    'text_file': text_filename,
                    'size': len(page_source)
                })
                print(f"  ✓ Success: {title[:60]}")
                success = True
            else:
                results.append({
                    'id': article_id,
                    'title': title,
                    'url': clean_url,
                    'status': 'partial: text extraction failed',
                    'html_file': filename,
                    'text_file': None,
                    'size': len(page_source)
                })
                print(f"  ⚠ Partial: Saved HTML only")
                success = True
                
        except Exception as e:
            retry_count += 1
            if retry_count >= max_retries:
                results.append({
                    'id': article_id,
                    'title': None,
                    'url': clean_url,
                    'status': f'failed: {str(e)[:100]}',
                    'html_file': None,
                    'text_file': None,
                    'size': 0
                })
                failed_urls.append(clean_url)
                print(f"  ✗ Failed after {max_retries} retries")
            else:
                time.sleep(2)  # Wait before retry

driver.quit()

# Save metadata
metadata = {
    'download_date': time.strftime('%Y-%m-%d %H:%M:%S'),
    'total_articles': len(urls),
    'successful_downloads': len([r for r in results if r['status'] == 'success']),
    'partial_downloads': len([r for r in results if 'partial' in r['status']]),
    'failed_downloads': len([r for r in results if 'failed' in r['status']]),
    'articles': results,
    'failed_urls': failed_urls
}

with open(output_dir / 'metadata.json', 'w', encoding='utf-8') as f:
    json.dump(metadata, f, indent=2)

print(f"\n{'='*80}")
print(f"Download Complete!")
print(f"✓ Success: {metadata['successful_downloads']}/{metadata['total_articles']}")
print(f"⚠ Partial: {metadata['partial_downloads']}")
print(f"✗ Failed: {metadata['failed_downloads']}")
print(f"\nFiles saved to: {output_dir.absolute()}")
print(f"Metadata saved to: {output_dir / 'metadata.json'}")

if failed_urls:
    print(f"\nFailed URLs (try manually):")
    for url in failed_urls:
        print(f"  - {url}")