A 403 error typically means "Forbidden" - the server is rejecting your requests. AO3 (Archive of Our Own) likely has anti-bot measures in place that are detecting and blocking your automated requests.
Here are the most common reasons and potential solutions:
Rate limiting: You're making too many requests too quickly. AO3 probably has strict rate limits to prevent scraping.
Bot detection: Even with a User-Agent header, your request pattern might look automated. Multiple simultaneous requests from the same IP are a dead giveaway.
Missing headers: AO3 might expect additional headers that real browsers send.
Try these modifications:
import asyncio
import aiohttp
from bs4 import BeautifulSoup
import random
def clean_url(url):
url = url.strip()
return url
HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.5",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"Upgrade-Insecure-Requests": "1",
}
async def fetch_word_count(session, url):
url = clean_url(url)
try:
# Add random delay between requests
await asyncio.sleep(random.uniform(1, 3))
async with session.get(url, headers=HEADERS) as response:
if response.status != 200:
print(f"Failed to fetch {url} (status {response.status})")
return 0
html = await response.text()
soup = BeautifulSoup(html, 'html.parser')
word_tag = soup.find('dd', class_='words')
if word_tag:
return int(word_tag.get_text(strip=True).replace(',', ''))
except Exception as e:
print(f"Error with {url}: {e}")
return 0
async def main(file_path):
with open(file_path, 'r') as f:
urls = list({clean_url(line) for line in f if line.strip()})
# Process URLs sequentially instead of all at once
word_counts = []
async with aiohttp.ClientSession(headers=HEADERS) as session:
for url in urls:
count = await fetch_word_count(session, url)
word_counts.append(count)
print(f"{url} -> {count} words")
total = sum(word_counts)
print(f"\nTotal word count: {total}")
if __name__ == '__main__':
asyncio.run(main('fic_urls.txt'))
The key changes are adding delays between requests and processing URLs sequentially rather than concurrently. If this still fails, you might need to respect AO3's robots.txt and terms of service, or consider using their official API if available.