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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import trafilatura
|
| 2 |
+
import requests
|
| 3 |
+
import time
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
from urllib.parse import urljoin
|
| 6 |
+
import csv
|
| 7 |
+
import json
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 11 |
+
from queue import Queue
|
| 12 |
+
import threading
|
| 13 |
+
from requests.adapters import HTTPAdapter
|
| 14 |
+
from requests.packages.urllib3.util.retry import Retry
|
| 15 |
+
|
| 16 |
+
class ArticleScraper:
|
| 17 |
+
def __init__(self, base_url):
|
| 18 |
+
self.base_url = base_url
|
| 19 |
+
self.headers = {
|
| 20 |
+
'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'
|
| 21 |
+
}
|
| 22 |
+
self.articles = []
|
| 23 |
+
self.csv_lock = threading.Lock()
|
| 24 |
+
self.session = self._create_session()
|
| 25 |
+
|
| 26 |
+
def _create_session(self):
|
| 27 |
+
"""Create a session with retry strategy"""
|
| 28 |
+
session = requests.Session()
|
| 29 |
+
retry_strategy = Retry(
|
| 30 |
+
total=3,
|
| 31 |
+
backoff_factor=1,
|
| 32 |
+
status_forcelist=[429, 500, 502, 503, 504]
|
| 33 |
+
)
|
| 34 |
+
adapter = HTTPAdapter(max_retries=retry_strategy, pool_connections=100, pool_maxsize=100)
|
| 35 |
+
session.mount("http://", adapter)
|
| 36 |
+
session.mount("https://", adapter)
|
| 37 |
+
session.headers.update(self.headers)
|
| 38 |
+
return session
|
| 39 |
+
|
| 40 |
+
def get_article_urls_from_page(self, page_num):
|
| 41 |
+
"""Extract article URLs from a single page"""
|
| 42 |
+
try:
|
| 43 |
+
url = f"{self.base_url}?page={page_num}"
|
| 44 |
+
response = self.session.get(url, timeout=30)
|
| 45 |
+
response.raise_for_status()
|
| 46 |
+
|
| 47 |
+
# Use lxml parser for faster parsing
|
| 48 |
+
soup = BeautifulSoup(response.content, 'lxml')
|
| 49 |
+
|
| 50 |
+
# Use CSS selector for faster selection
|
| 51 |
+
tracks = soup.select('ul.listing li.track div.track-holder a[href]')
|
| 52 |
+
article_urls = [urljoin(self.base_url, a['href']) for a in tracks]
|
| 53 |
+
|
| 54 |
+
print(f"Found {len(article_urls)} articles on page {page_num}")
|
| 55 |
+
return article_urls
|
| 56 |
+
|
| 57 |
+
except Exception as e:
|
| 58 |
+
print(f"Error getting articles from page {page_num}: {str(e)}")
|
| 59 |
+
return []
|
| 60 |
+
|
| 61 |
+
def scrape_article(self, url):
|
| 62 |
+
"""Scrape content from a single article"""
|
| 63 |
+
try:
|
| 64 |
+
print(f"Scraping article: {url}")
|
| 65 |
+
# downloaded = trafilatura.fetch_url(url, session=self.session)
|
| 66 |
+
downloaded = self.session.get(url, timeout=30).content
|
| 67 |
+
|
| 68 |
+
if downloaded:
|
| 69 |
+
content = trafilatura.extract(downloaded,
|
| 70 |
+
include_links=False,
|
| 71 |
+
include_images=False,
|
| 72 |
+
include_tables=False,
|
| 73 |
+
include_formatting=False,
|
| 74 |
+
with_metadata=False,
|
| 75 |
+
output_format='txt')
|
| 76 |
+
|
| 77 |
+
if content:
|
| 78 |
+
cleaned_content = content.strip()
|
| 79 |
+
# Use lock when writing to CSV
|
| 80 |
+
with self.csv_lock:
|
| 81 |
+
with open('sorani.csv', 'a', encoding='utf-8', newline='') as f:
|
| 82 |
+
writer = csv.writer(f)
|
| 83 |
+
writer.writerow([cleaned_content])
|
| 84 |
+
return True
|
| 85 |
+
|
| 86 |
+
print(f"No content found for: {url}")
|
| 87 |
+
return False
|
| 88 |
+
|
| 89 |
+
except Exception as e:
|
| 90 |
+
print(f"Error scraping article {url}: {str(e)}")
|
| 91 |
+
return False
|
| 92 |
+
|
| 93 |
+
def scrape_urls_batch(self, urls):
|
| 94 |
+
"""Scrape a batch of URLs"""
|
| 95 |
+
for url in urls:
|
| 96 |
+
self.scrape_article(url)
|
| 97 |
+
|
| 98 |
+
def scrape_all_pages(self, start_page, end_page):
|
| 99 |
+
"""Scrape articles from all pages using parallel processing"""
|
| 100 |
+
total_articles = 0
|
| 101 |
+
successful_articles = 0
|
| 102 |
+
all_urls = []
|
| 103 |
+
|
| 104 |
+
print(f"Starting scraping from page {start_page} to {end_page}")
|
| 105 |
+
|
| 106 |
+
# First gather all URLs using ThreadPoolExecutor
|
| 107 |
+
print("Gathering all article URLs...")
|
| 108 |
+
with ThreadPoolExecutor(max_workers=10) as executor:
|
| 109 |
+
future_to_page = {
|
| 110 |
+
executor.submit(self.get_article_urls_from_page, page_num): page_num
|
| 111 |
+
for page_num in range(start_page, end_page + 1)
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
for future in as_completed(future_to_page):
|
| 115 |
+
page_urls = future.result()
|
| 116 |
+
all_urls.extend(page_urls)
|
| 117 |
+
total_articles += len(page_urls)
|
| 118 |
+
|
| 119 |
+
print(f"Found total of {len(all_urls)} articles. Starting content scraping...")
|
| 120 |
+
|
| 121 |
+
# Then scrape all articles using ThreadPoolExecutor
|
| 122 |
+
# Split URLs into batches for better memory management
|
| 123 |
+
batch_size = 50
|
| 124 |
+
url_batches = [all_urls[i:i + batch_size] for i in range(0, len(all_urls), batch_size)]
|
| 125 |
+
|
| 126 |
+
with ThreadPoolExecutor(max_workers=20) as executor:
|
| 127 |
+
futures = [executor.submit(self.scrape_urls_batch, batch) for batch in url_batches]
|
| 128 |
+
|
| 129 |
+
for future in as_completed(futures):
|
| 130 |
+
try:
|
| 131 |
+
future.result()
|
| 132 |
+
except Exception as e:
|
| 133 |
+
print(f"Batch processing error: {str(e)}")
|
| 134 |
+
|
| 135 |
+
print(f"\nScraping completed!")
|
| 136 |
+
print(f"Total articles found: {total_articles}")
|
| 137 |
+
|
| 138 |
+
# Verify and clean the CSV file
|
| 139 |
+
self.verify_and_clean_csv()
|
| 140 |
+
|
| 141 |
+
def verify_and_clean_csv(self):
|
| 142 |
+
"""Verify the CSV file and remove any duplicate or empty rows"""
|
| 143 |
+
try:
|
| 144 |
+
# Read the CSV file in chunks to handle large files
|
| 145 |
+
chunk_size = 10000
|
| 146 |
+
chunks = []
|
| 147 |
+
for chunk in pd.read_csv('sorani.csv', chunksize=chunk_size):
|
| 148 |
+
chunks.append(chunk)
|
| 149 |
+
df = pd.concat(chunks)
|
| 150 |
+
|
| 151 |
+
# Remove duplicates and empty rows
|
| 152 |
+
initial_rows = len(df)
|
| 153 |
+
df.drop_duplicates(subset=['articles'], keep='first', inplace=True)
|
| 154 |
+
df.dropna(subset=['articles'], inplace=True)
|
| 155 |
+
df = df[df['articles'].str.strip() != '']
|
| 156 |
+
|
| 157 |
+
# Save the cleaned data
|
| 158 |
+
df.to_csv('sorani.csv', index=False, encoding='utf-8')
|
| 159 |
+
|
| 160 |
+
print(f"\nCSV Cleaning Results:")
|
| 161 |
+
print(f"Initial rows: {initial_rows}")
|
| 162 |
+
print(f"Final rows after cleaning: {len(df)}")
|
| 163 |
+
|
| 164 |
+
except Exception as e:
|
| 165 |
+
print(f"Error during CSV cleaning: {str(e)}")
|
| 166 |
+
|
| 167 |
+
def main():
|
| 168 |
+
# base_url = "https://anfsorani.com/zhyawa-swwrya"
|
| 169 |
+
# base_url = "https://anfsorani.com/zhhhaty-nawhast"
|
| 170 |
+
# base_url = "https://anfsorani.com/جیهان"
|
| 171 |
+
base_url = "https://anfsorani.com/witar"
|
| 172 |
+
start_page = 1
|
| 173 |
+
end_page = 20
|
| 174 |
+
|
| 175 |
+
scraper = ArticleScraper(base_url)
|
| 176 |
+
scraper.scrape_all_pages(start_page, end_page)
|
| 177 |
+
|
| 178 |
+
if __name__ == "__main__":
|
| 179 |
+
main()
|