-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathai_server.py
More file actions
1524 lines (1288 loc) · 68.1 KB
/
ai_server.py
File metadata and controls
1524 lines (1288 loc) · 68.1 KB
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# AI Company Data Crawler with FastAPI and Real Libraries
# This system extracts comprehensive company information from websites
import asyncio
import csv
import time
from datetime import datetime
from typing import List, Dict, Optional
import re
import logging
from pathlib import Path
import json
import socket
from contextlib import asynccontextmanager
from fastapi import FastAPI, UploadFile, File, HTTPException
from fastapi.responses import FileResponse
from pydantic import BaseModel
from selenium import webdriver
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 selenium.common.exceptions import TimeoutException, NoSuchElementException
import pandas as pd
import requests
from bs4 import BeautifulSoup
import aiohttp
from urllib.parse import urljoin, urlparse
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class CompanyData(BaseModel):
company_name: str
website: str = ""
phone_number: str = ""
street_address: str = ""
city: str = ""
state: str = ""
zip_code: str = ""
facebook_page: str = ""
facebook_page_name: str = ""
facebook_likes: str = ""
facebook_about: str = ""
linkedin_page: str = ""
public_email: str = ""
contact_person: str = ""
processing_time: float = 0.0
status: str = ""
last_updated: str = ""
class CompanyCrawler:
def __init__(self):
self.driver = None
self.session = None
async def initialize_session(self):
"""Initialize aiohttp session for web requests"""
connector = aiohttp.TCPConnector(limit=10, limit_per_host=3)
timeout = aiohttp.ClientTimeout(total=30)
self.session = aiohttp.ClientSession(
connector=connector,
timeout=timeout,
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
)
def setup_headless_browser(self):
"""Setup optimized headless Chrome browser"""
try:
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--window-size=1920,1080")
chrome_options.add_argument("--disable-blink-features=AutomationControlled")
chrome_options.add_argument("--disable-extensions")
chrome_options.add_argument("--disable-plugins")
chrome_options.add_argument("--disable-images")
chrome_options.add_argument("--disable-javascript") # Faster loading
chrome_options.add_argument("--disable-web-security")
chrome_options.add_argument("--disable-features=VizDisplayCompositor")
chrome_options.add_argument("--page-load-strategy=eager") # Don't wait for all resources
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option('useAutomationExtension', False)
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")
# Aggressive logging suppression
chrome_options.add_argument("--log-level=3")
chrome_options.add_argument("--silent")
chrome_options.add_argument("--disable-logging")
chrome_options.add_experimental_option('excludeSwitches', ['enable-logging'])
# Set page load timeout at driver level
self.driver = webdriver.Chrome(options=chrome_options)
self.driver.set_page_load_timeout(5) # 5 second page load timeout
self.driver.implicitly_wait(3) # 3 second element wait
self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
logger.info("Chrome browser initialized successfully")
return self.driver
except Exception as e:
logger.error(f"Error setting up Chrome browser: {str(e)}")
self.driver = None
return None
def close_browser(self):
"""Close the headless browser"""
if self.driver:
self.driver.quit()
self.driver = None
async def find_website_fallback(self, company_name: str) -> str:
"""Improved fallback method to find website without browser"""
try:
# Clean company name and create better domain patterns
company_clean = re.sub(r'[^a-zA-Z0-9\s]', '', company_name.lower())
words = [word for word in company_clean.split() if len(word) > 2] # Filter short words
# Generate more intelligent domain patterns
potential_domains = []
if len(words) >= 1:
# Primary patterns
if len(words) >= 2:
potential_domains.extend([
f"{''.join(words[:2])}.com",
f"{words[0]}{words[1]}.com",
f"{'-'.join(words[:2])}.com",
f"{words[0]}-{words[1]}.com"
])
# Single word patterns
potential_domains.extend([
f"{words[0]}.com",
f"{words[0]}inc.com",
f"{words[0]}llc.com"
])
# Healthcare specific patterns
if any(health_word in company_name.lower() for health_word in ['health', 'care', 'medical', 'hospice']):
if len(words) >= 2:
potential_domains.extend([
f"{words[0]}health.com",
f"{words[0]}care.com",
f"{words[0]}medical.com"
])
# Remove duplicates while preserving order
seen = set()
unique_domains = []
for domain in potential_domains:
if domain not in seen and len(domain) > 6: # Avoid too short domains
seen.add(domain)
unique_domains.append(domain)
# Test each potential domain with content validation
for domain in unique_domains[:8]: # Limit to top 8 candidates
for protocol in ['https://', 'http://']:
test_url = protocol + domain
try:
if not self.session:
await self.initialize_session()
async with self.session.get(test_url, timeout=aiohttp.ClientTimeout(total=10)) as response:
if response.status == 200:
content = await response.text()
# Validate the website actually relates to the company
if await self.validate_website_relevance(company_name, content, test_url):
logger.info(f"Found and validated website for {company_name}: {test_url}")
return test_url
except Exception:
continue
return ""
except Exception as e:
logger.error(f"Error in fallback website search for {company_name}: {str(e)}")
return ""
async def validate_website_relevance(self, company_name: str, html_content: str, url: str) -> bool:
"""Validate if the found website actually belongs to the company"""
try:
# Skip validation for very generic domains
domain = urlparse(url).netloc.lower()
generic_domains = ['angel.com', 'angels.com', 'anchor.com', 'care.com', 'health.com']
if domain in generic_domains:
return False
# Check if company name appears in the content
company_words = [word.lower() for word in re.findall(r'\b\w+\b', company_name) if len(word) > 3]
content_lower = html_content.lower()
# Count how many significant company words appear in content
matches = sum(1 for word in company_words if word in content_lower)
# Require at least 1 significant word match for healthcare companies
# or 2 word matches for other companies
threshold = 1 if any(hw in company_name.lower() for hw in ['health', 'care', 'medical', 'hospice']) else 2
return matches >= threshold
except Exception:
return True # If validation fails, assume it's valid
async def find_website_browser(self, company_name: str) -> str:
"""Optimized browser-based website discovery with faster timeouts"""
try:
if not self.driver:
self.setup_headless_browser()
if not self.driver:
return ""
# Simplified, faster search query
search_query = f'"{company_name}" site:*.com'
search_url = f"https://www.google.com/search?q={requests.utils.quote(search_query)}"
logger.info(f"Quick search for: {company_name}")
try:
# Very aggressive timeout - if Google is slow, skip to fallback
self.driver.get(search_url)
wait = WebDriverWait(self.driver, 3) # Only 3 seconds
search_results = wait.until(
EC.presence_of_all_elements_located((By.CSS_SELECTOR, "div.g"))
)
# Process only the first result quickly
for result in search_results[:1]: # Only check first result
try:
link_element = result.find_element(By.CSS_SELECTOR, "a[href]")
url = link_element.get_attribute("href")
if url and url.startswith("http") and not url.startswith("https://www.google"):
# Quick domain check
domain = urlparse(url).netloc.lower().replace('www.', '')
skip_domains = ['wikipedia', 'linkedin', 'facebook', 'twitter', 'yelp', 'yellowpages']
if not any(skip in domain for skip in skip_domains):
logger.info(f"Quick find for {company_name}: {url}")
return url
except (NoSuchElementException, AttributeError):
continue
except TimeoutException:
logger.info(f"Quick search timeout for {company_name} - using fallback")
return ""
except Exception as e:
logger.warning(f"Browser error for {company_name}: {str(e)}")
self.close_browser()
return ""
return ""
except Exception as e:
logger.error(f"Critical browser error for {company_name}: {str(e)}")
self.close_browser()
return ""
async def find_company_website(self, company_name: str) -> str:
"""Use headless browser to find company website via Google search"""
website = await self.find_website_browser(company_name)
if not website:
logger.info(f"Browser search failed for {company_name}, trying fallback method")
website = await self.find_website_fallback(company_name)
return website
async def extract_company_info_with_ai(self, website_url: str, html_content: str) -> Dict[str, str]:
"""Enhanced company information extraction with better patterns"""
try:
soup = BeautifulSoup(html_content, 'html.parser')
info = {}
text_content = soup.get_text()
# Enhanced phone number extraction
phone_patterns = [
r'\b(?:\+?1[-.\s]?)?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})\b',
r'\b([0-9]{3})[-.\s]([0-9]{3})[-.\s]([0-9]{4})\b',
r'\b\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})\b'
]
for pattern in phone_patterns:
matches = re.findall(pattern, text_content)
if matches:
match = matches[0]
if len(match) == 3: # Tuple format
phone = f"({match[0]}) {match[1]}-{match[2]}"
# Validate it's a reasonable phone number
if not phone.startswith(('(000)', '(111)', '(123)', '(555)')):
info['phone_number'] = phone
break
# Enhanced email extraction with better filtering
email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
emails = re.findall(email_pattern, text_content)
if emails:
# Better email filtering
filtered_emails = []
for email in emails:
if not any(skip in email.lower() for skip in [
'noreply', 'no-reply', 'donotreply', 'newsletter', 'unsubscribe',
'support@example', 'test@', 'example@', 'admin@example',
'webmaster@', 'postmaster@', 'abuse@'
]):
filtered_emails.append(email)
if filtered_emails:
# Prefer contact/info emails
priority_emails = [e for e in filtered_emails if any(word in e.lower() for word in ['contact', 'info', 'hello', 'office'])]
info['public_email'] = priority_emails[0] if priority_emails else filtered_emails[0]
# Enhanced social media detection
for link in soup.find_all('a', href=True):
href = link.get('href').lower()
if 'facebook.com' in href and not any(skip in href for skip in ['/pages/', '/groups/', '/sharer', '/login']):
# Clean Facebook URL
fb_url = href.split('?')[0].split('#')[0] # Remove parameters
if fb_url.count('/') >= 3: # Valid FB page structure
info['facebook_page'] = fb_url
elif 'linkedin.com/company' in href or 'linkedin.com/in' in href:
# Clean LinkedIn URL
li_url = href.split('?')[0].split('#')[0]
info['linkedin_page'] = li_url
# Enhanced address extraction
self._extract_address_info(soup, info)
# Enhanced contact person extraction
self._extract_contact_person(soup, info)
# Extract city and state from various sources
self._extract_location_info(soup, info)
return info
except Exception as e:
logger.error(f"Error extracting info with AI from {website_url}: {str(e)}")
return {}
def _extract_address_info(self, soup: BeautifulSoup, info: Dict[str, str]):
"""Extract address information with multiple strategies"""
try:
text_content = soup.get_text()
# Strategy 1: Look for structured address patterns
address_patterns = [
r'(\d+\s+[A-Za-z\s]+(?:Street|St|Avenue|Ave|Road|Rd|Drive|Dr|Boulevard|Blvd|Lane|Ln|Way|Circle|Cir|Court|Ct)\.?)\s*,?\s*([A-Za-z\s]+),?\s*([A-Z]{2})\s+(\d{5}(?:-\d{4})?)',
r'(\d+\s+[A-Za-z\s]+(?:St|Ave|Rd|Dr|Blvd|Ln|Way|Cir|Ct)\.?)\s*,?\s*([A-Za-z\s]+),?\s*([A-Z]{2})\s+(\d{5})'
]
for pattern in address_patterns:
matches = re.findall(pattern, text_content, re.IGNORECASE)
if matches:
match = matches[0]
info['street_address'] = match[0].strip()
info['city'] = match[1].strip()
info['state'] = match[2].strip()
info['zip_code'] = match[3].strip()
return
# Strategy 2: Look near address indicators
address_indicators = ['address', 'location', 'office', 'headquarters', 'visit us', 'our location']
for indicator in address_indicators:
sections = soup.find_all(string=re.compile(indicator, re.I))
for section in sections:
parent = section.parent
if parent:
address_text = parent.get_text()
# Extract components separately
zip_match = re.search(r'\b(\d{5}(?:-\d{4})?)\b', address_text)
if zip_match and 'zip_code' not in info:
info['zip_code'] = zip_match.group(1)
state_match = re.search(r'\b([A-Z]{2})\b', address_text)
if state_match and 'state' not in info:
info['state'] = state_match.group(1)
street_match = re.search(r'\b(\d+\s+[A-Za-z\s]+(?:Street|St|Avenue|Ave|Road|Rd|Drive|Dr|Boulevard|Blvd|Lane|Ln|Way|Circle|Cir|Court|Ct)\.?)', address_text, re.I)
if street_match and 'street_address' not in info:
info['street_address'] = street_match.group(1).strip()
except Exception:
pass
def _extract_contact_person(self, soup: BeautifulSoup, info: Dict[str, str]):
"""Extract contact person with better accuracy"""
try:
contact_indicators = [
'chief executive officer', 'ceo', 'president', 'founder', 'owner',
'contact person', 'manager', 'director', 'administrator'
]
for indicator in contact_indicators:
sections = soup.find_all(string=re.compile(indicator, re.I))
for section in sections:
parent = section.parent
if parent:
# Look for name patterns near indicators
text = parent.get_text()
# More specific name pattern
name_patterns = [
r'(?:CEO|President|Founder|Director|Manager)[:\s]+([A-Z][a-z]+\s+[A-Z][a-z]+)',
r'([A-Z][a-z]+\s+[A-Z][a-z]+)[,\s]+(?:CEO|President|Founder|Director|Manager)',
r'\b([A-Z][a-z]{2,}\s+[A-Z][a-z]{2,})\b' # Two capitalized words
]
for pattern in name_patterns:
names = re.findall(pattern, text)
if names:
# Filter out common false positives
valid_names = [name for name in names if not any(
word in name.lower() for word in ['home', 'care', 'health', 'services', 'medical', 'company']
)]
if valid_names:
info['contact_person'] = valid_names[0]
return
except Exception:
pass
def _extract_location_info(self, soup: BeautifulSoup, info: Dict[str, str]):
"""Extract city and state information from various page elements"""
try:
text_content = soup.get_text()
# Look for city, state patterns
if 'city' not in info or 'state' not in info:
city_state_patterns = [
r'\b([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*),\s*([A-Z]{2})\b',
r'\bserving\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*),?\s*([A-Z]{2})\b',
r'\blocated\s+in\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*),?\s*([A-Z]{2})\b'
]
for pattern in city_state_patterns:
matches = re.findall(pattern, text_content)
if matches:
city, state = matches[0]
if 'city' not in info and len(city) > 2:
info['city'] = city.strip()
if 'state' not in info:
info['state'] = state.strip()
break
except Exception:
pass
async def fetch_website_content(self, url: str) -> str:
"""Enhanced website content fetching with better error handling"""
try:
if not self.session:
await self.initialize_session()
# Clean and normalize URL
if not url.startswith(('http://', 'https://')):
# Try both protocols with short timeout
for protocol in ['https://', 'http://']:
test_url = protocol + url
try:
async with self.session.get(
test_url,
timeout=aiohttp.ClientTimeout(total=8),
allow_redirects=True
) as response:
if response.status == 200:
content = await response.text()
# Basic content validation
if len(content) > 500 and '<html' in content.lower():
logger.info(f"Successfully fetched content from {test_url}")
return content
else:
logger.warning(f"Content too short or invalid from {test_url}")
except Exception as e:
logger.debug(f"Failed to fetch {test_url}: {str(e)}")
continue
return ""
else:
# URL already has protocol
try:
async with self.session.get(
url,
timeout=aiohttp.ClientTimeout(total=8),
allow_redirects=True
) as response:
if response.status == 200:
content = await response.text()
if len(content) > 500 and '<html' in content.lower():
logger.info(f"Successfully fetched content from {url}")
return content
else:
logger.warning(f"Content validation failed for {url}")
return ""
else:
logger.warning(f"HTTP {response.status} for {url}")
return ""
except Exception as e:
logger.warning(f"Error fetching {url}: {str(e)}")
return ""
except Exception as e:
logger.error(f"Critical error fetching {url}: {str(e)}")
return ""
async def extract_facebook_info(self, facebook_url: str) -> Dict[str, str]:
"""Extract Facebook page information using proven scraping techniques"""
result = {
'facebook_page_name': '',
'facebook_likes': '',
'facebook_about': ''
}
if not facebook_url:
logger.info(f"[FB SCRAPE] No facebook_url provided")
return result
# Ensure we have a browser
if not self.driver:
self.setup_headless_browser()
if not self.driver:
logger.warning(f"[FB SCRAPE] Could not initialize browser")
return self.extract_facebook_from_url(facebook_url)
try:
clean_url = facebook_url.split('?')[0].split('#')[0]
if not clean_url.startswith('http'):
clean_url = 'https://' + clean_url
logger.info(f"[FB SCRAPE] Scraping Facebook page: {clean_url}")
# Set timeouts
self.driver.set_page_load_timeout(15)
self.driver.get(clean_url)
# Wait for page to load
WebDriverWait(self.driver, 10).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
page_title = self.driver.title
logger.info(f"[FB SCRAPE] Page title: {page_title}")
# Detect login page
if any(x in page_title for x in ["Log into Facebook", "Facebook – log in", "Facebook - log in"]):
logger.warning(f"[FB SCRAPE] Facebook page {clean_url} requires login. Title: {page_title}")
return self.extract_facebook_from_url(facebook_url)
# Check for login wall in body text
try:
body_text = self.driver.find_element(By.TAG_NAME, "body").text
logger.info(f"[FB SCRAPE] Body text (first 200 chars): {body_text[:200]}")
if "You must log in" in body_text or "See more of" in body_text:
logger.warning(f"[FB SCRAPE] Facebook page {clean_url} is not public. Body contains login wall.")
return self.extract_facebook_from_url(facebook_url)
except Exception as e:
logger.warning(f"[FB SCRAPE] Could not read body text: {e}")
# Strategy 1: Try meta tags first (most reliable)
try:
og_title_elements = self.driver.find_elements(By.XPATH, '//meta[@property="og:title"]')
if og_title_elements:
content = og_title_elements[0].get_attribute('content')
logger.info(f"[FB SCRAPE] og:title: {content}")
if content and content.strip():
result['facebook_page_name'] = content.strip()
else:
logger.info(f"[FB SCRAPE] No og:title meta tag found.")
og_desc_elements = self.driver.find_elements(By.XPATH, '//meta[@property="og:description"]')
if og_desc_elements:
content = og_desc_elements[0].get_attribute('content')
logger.info(f"[FB SCRAPE] og:description: {content}")
if content and content.strip() and len(content.strip()) > 10:
result['facebook_about'] = content.strip()[:300]
else:
logger.info(f"[FB SCRAPE] No og:description meta tag found.")
except Exception as e:
logger.warning(f"[FB SCRAPE] Exception reading meta tags: {e}")
# Strategy 2: Fallback to title and h1 elements
if not result['facebook_page_name']:
try:
# Clean up page title
clean_title = page_title.replace(" | Facebook", "").replace(" - Facebook", "").strip()
if clean_title and clean_title != "Facebook":
result['facebook_page_name'] = clean_title
logger.info(f"[FB SCRAPE] Using cleaned title: {clean_title}")
# Try h1 elements
headings = self.driver.find_elements(By.XPATH, '//h1')
for heading in headings:
h1_text = heading.text.strip()
if h1_text and len(h1_text) > 0 and len(h1_text) < 100:
logger.info(f"[FB SCRAPE] h1 found: {h1_text}")
result['facebook_page_name'] = h1_text
break
if not result['facebook_page_name']:
logger.info(f"[FB SCRAPE] No suitable h1 found.")
except Exception as e:
logger.warning(f"[FB SCRAPE] Exception reading h1/title: {e}")
# Strategy 3: Look for likes/followers in visible text
try:
# Enhanced XPath for likes/followers
like_xpath_patterns = [
"//*[contains(text(),'like') or contains(text(),'Like')]",
"//*[contains(text(),'follower') or contains(text(),'Follower')]",
"//*[contains(text(),'fan') or contains(text(),'Fan')]",
"//*[contains(@aria-label,'like') or contains(@aria-label,'follower')]"
]
found_like = False
for xpath_pattern in like_xpath_patterns:
try:
like_elements = self.driver.find_elements(By.XPATH, xpath_pattern)
for elem in like_elements:
text = elem.text.strip()
if text and len(text) < 100: # Reasonable length
logger.info(f"[FB SCRAPE] Like/follower element: {text}")
# Look for number patterns in the text
number_patterns = [
r'(\d+(?:,\d+)*(?:\.\d+)?[KkMm]?)\s*(?:people\s+)?(?:like|follow|fan)',
r'(\d+(?:,\d+)*)\s*(?:likes|followers|fans)'
]
for pattern in number_patterns:
matches = re.findall(pattern, text, re.IGNORECASE)
if matches:
result['facebook_likes'] = f"{matches[0]} likes"
logger.info(f"[FB SCRAPE] Extracted likes: {result['facebook_likes']}")
found_like = True
break
if found_like:
break
if found_like:
break
except Exception as e:
logger.debug(f"[FB SCRAPE] Error with xpath pattern {xpath_pattern}: {e}")
continue
if not found_like:
logger.info(f"[FB SCRAPE] No like/follower text found in visible elements.")
except Exception as e:
logger.warning(f"[FB SCRAPE] Exception reading likes/followers: {e}")
# Strategy 4: Look for about information in various places
if not result['facebook_about']:
try:
about_selectors = [
"[data-testid='intro_card']",
".about-section",
"[data-overviewsection='about']",
".bio",
".description"
]
for selector in about_selectors:
try:
about_elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
for element in about_elements:
about_text = element.text.strip()
if about_text and len(about_text) > 20:
result['facebook_about'] = about_text[:300]
logger.info(f"[FB SCRAPE] Found about text: {about_text[:50]}...")
break
if result['facebook_about']:
break
except Exception as e:
logger.debug(f"[FB SCRAPE] Error with selector {selector}: {e}")
continue
except Exception as e:
logger.warning(f"[FB SCRAPE] Exception reading about section: {e}")
except Exception as e:
logger.warning(f"[FB SCRAPE] Failed to scrape Facebook page {facebook_url}: {e}")
# Fallback to URL extraction
return self.extract_facebook_from_url(facebook_url)
# If we didn't get a name, try URL extraction as fallback
if not result['facebook_page_name']:
url_result = self.extract_facebook_from_url(facebook_url)
result.update(url_result)
logger.info(f"[FB SCRAPE] Final extracted result: {result}")
return result
async def try_simple_facebook_extraction(self, facebook_url: str) -> Dict[str, str]:
"""Simple attempt at Facebook extraction with timeout"""
fb_info = {}
try:
if not self.driver:
self.setup_headless_browser()
if not self.driver:
return {}
clean_url = facebook_url.split('?')[0].split('#')[0]
if not clean_url.startswith('http'):
clean_url = 'https://' + clean_url
# Very short timeout - if it doesn't work quickly, give up
self.driver.set_page_load_timeout(5)
self.driver.get(clean_url)
time.sleep(2)
# Try to get page title only
title = self.driver.title
if title and 'Facebook' in title:
page_name = title.replace(' | Facebook', '').replace(' - Facebook', '').strip()
if page_name and len(page_name) > 2:
fb_info['facebook_page_name'] = page_name
return fb_info
except Exception:
# Facebook blocked us - this is expected
return {}
async def extract_facebook_with_browser(self, facebook_url: str) -> Dict[str, str]:
"""Extract Facebook info using existing browser with enhanced techniques"""
fb_info = {}
try:
# Clean up the Facebook URL
clean_url = facebook_url.split('?')[0].split('#')[0]
if not clean_url.startswith('http'):
clean_url = 'https://' + clean_url
logger.info(f"Extracting Facebook data from: {clean_url}")
# Set longer timeout for Facebook
self.driver.set_page_load_timeout(15)
# Try mobile version first (often has more accessible data)
mobile_url = clean_url.replace('www.facebook.com', 'm.facebook.com')
try:
self.driver.get(mobile_url)
time.sleep(8)
# Extract from mobile version
mobile_data = self._extract_facebook_mobile(self.driver)
if mobile_data:
fb_info.update(mobile_data)
except Exception as e:
logger.warning(f"Mobile Facebook extraction failed: {str(e)}")
# If mobile didn't work or didn't get all data, try desktop
if not fb_info.get('facebook_page_name') or not fb_info.get('facebook_likes'):
try:
self.driver.get(clean_url)
time.sleep(8)
desktop_data = self._extract_facebook_desktop(self.driver)
if desktop_data:
fb_info.update(desktop_data)
except Exception as e:
logger.warning(f"Desktop Facebook extraction failed: {str(e)}")
# Try Graph API approach (public data only)
if not fb_info.get('facebook_about'):
graph_data = await self._extract_facebook_graph_api(clean_url)
if graph_data:
fb_info.update(graph_data)
return fb_info
except Exception as e:
logger.error(f"Error extracting Facebook info with browser: {str(e)}")
return {}
def _extract_facebook_mobile(self, driver) -> Dict[str, str]:
"""Extract from mobile Facebook version"""
fb_info = {}
try:
# Mobile page name extraction
mobile_name_selectors = [
"h1",
".bi",
"#cover-name",
"[data-sigil='profile-name']"
]
for selector in mobile_name_selectors:
try:
element = driver.find_element(By.CSS_SELECTOR, selector)
text = element.text.strip()
if text and len(text) > 0 and len(text) < 100:
fb_info['facebook_page_name'] = text
logger.info(f"Found mobile Facebook page name: {text}")
break
except NoSuchElementException:
continue
# Mobile likes extraction - look in page source
page_source = driver.page_source
# More comprehensive like patterns for mobile
mobile_like_patterns = [
r'(\d+(?:,\d+)*(?:\.\d+)?[KkMm]?)\s*(?:people\s+)?(?:like|follow|fan)',
r'(\d+(?:,\d+)*)\s*(?:Likes|Followers|People)',
r'"likeCount["\']?\s*[:=]\s*(\d+)',
r'"followerCount["\']?\s*[:=]\s*(\d+)',
r'(\d+[KkMm]?)\s+(?:likes|followers)'
]
for pattern in mobile_like_patterns:
matches = re.findall(pattern, page_source, re.IGNORECASE)
if matches:
fb_info['facebook_likes'] = matches[0] + " likes"
logger.info(f"Found mobile Facebook likes: {fb_info['facebook_likes']}")
break
# Mobile about extraction
about_selectors = [
"[data-sigil='profile-description']",
".bio",
".about",
"[data-testid='intro_card']"
]
for selector in about_selectors:
try:
element = driver.find_element(By.CSS_SELECTOR, selector)
text = element.text.strip()
if text and len(text) > 10:
fb_info['facebook_about'] = text[:300]
logger.info(f"Found mobile Facebook about: {text[:50]}...")
break
except NoSuchElementException:
continue
return fb_info
except Exception as e:
logger.error(f"Error in mobile Facebook extraction: {str(e)}")
return {}
def _extract_facebook_desktop(self, driver) -> Dict[str, str]:
"""Extract from desktop Facebook version with enhanced selectors"""
fb_info = {}
try:
page_source = driver.page_source
# Desktop page name
if not fb_info.get('facebook_page_name'):
desktop_name_selectors = [
"h1[data-testid='page-header-title']",
"h1.x1heor9g",
"h1",
"title"
]
for selector in desktop_name_selectors:
try:
element = driver.find_element(By.CSS_SELECTOR, selector)
text = element.text.strip() if selector != "title" else element.get_attribute("innerHTML").strip()
if text and len(text) > 0 and len(text) < 100:
# Clean up title text
if selector == "title":
text = text.replace(" | Facebook", "").replace(" - Facebook", "")
fb_info['facebook_page_name'] = text
logger.info(f"Found desktop Facebook page name: {text}")
break
except NoSuchElementException:
continue
# Enhanced likes extraction with JSON parsing
json_patterns = [
r'"fan_count["\']?\s*[:=]\s*(\d+)',
r'"follower_count["\']?\s*[:=]\s*(\d+)',
r'"likes["\']?\s*[:=]\s*(\d+)',
r'"page_likers["\']?\s*[:=]\s*(\d+)'
]
for pattern in json_patterns:
matches = re.findall(pattern, page_source, re.IGNORECASE)
if matches:
count = int(matches[0])
if count > 0:
# Format large numbers
if count >= 1000000:
formatted = f"{count/1000000:.1f}M"
elif count >= 1000:
formatted = f"{count/1000:.1f}K"
else:
formatted = str(count)
fb_info['facebook_likes'] = f"{formatted} likes"
logger.info(f"Found desktop Facebook likes: {fb_info['facebook_likes']}")
break
# Enhanced about extraction
about_patterns_source = [
r'"description["\']?\s*[:=]\s*["\']([^"\']{20,300})["\']',
r'"about["\']?\s*[:=]\s*["\']([^"\']{20,300})["\']',
r'"bio["\']?\s*[:=]\s*["\']([^"\']{20,300})["\']',
r'content["\']?\s*[:=]\s*["\']([^"\']{20,300})["\']'
]
for pattern in about_patterns_source:
matches = re.findall(pattern, page_source, re.IGNORECASE | re.DOTALL)
if matches:
about_text = matches[0].strip()
# Clean up escape characters
about_text = about_text.replace('\\n', ' ').replace('\\t', ' ')
about_text = re.sub(r'\s+', ' ', about_text)
if len(about_text) > 20:
fb_info['facebook_about'] = about_text[:300]
logger.info(f"Found desktop Facebook about: {about_text[:50]}...")
break
return fb_info
except Exception as e:
logger.error(f"Error in desktop Facebook extraction: {str(e)}")
return {}
async def _extract_facebook_graph_api(self, facebook_url: str) -> Dict[str, str]:
"""Try to extract public Facebook data using Graph API approach"""
fb_info = {}
try:
# Extract page ID or username from URL
url_parts = facebook_url.replace('https://', '').replace('http://', '')
url_parts = url_parts.replace('www.facebook.com/', '').replace('m.facebook.com/', '')
page_id = url_parts.split('/')[0].split('?')[0]
if page_id and page_id not in ['profile.php', 'pages', 'people']:
# Try to get basic public info (this often works for business pages)
graph_url = f"https://graph.facebook.com/{page_id}?fields=name,about,fan_count&access_token="
# Note: This requires a valid access token, but we can try the public endpoint
public_url = f"https://www.facebook.com/{page_id}/about"
try:
if not self.session:
await self.initialize_session()
async with self.session.get(public_url, timeout=aiohttp.ClientTimeout(total=10)) as response:
if response.status == 200:
content = await response.text()
# Look for structured data in the about page
structured_patterns = [
r'"name"\s*:\s*"([^"]{5,100})"',
r'"description"\s*:\s*"([^"]{20,300})"',
r'"about"\s*:\s*"([^"]{20,300})"'
]
for i, pattern in enumerate(structured_patterns):
matches = re.findall(pattern, content, re.IGNORECASE)
if matches:
if i == 0 and not fb_info.get('facebook_page_name'):
fb_info['facebook_page_name'] = matches[0]
elif i > 0 and not fb_info.get('facebook_about'):
fb_info['facebook_about'] = matches[0][:300]
except Exception as e:
logger.debug(f"Graph API approach failed: {str(e)}")
return fb_info
except Exception as e:
logger.error(f"Error in Graph API extraction: {str(e)}")
return {}
async def extract_facebook_fresh_browser(self, facebook_url: str) -> Dict[str, str]:
"""Try Facebook extraction with a fresh browser instance"""
temp_driver = None
fb_info = {}
try:
# Create a fresh browser instance with different settings
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")