It looks like you're encountering a TypeError in your web crawler code:
TypeError: Population must be a sequence. For dicts or sets, use sorted(d).
This error arises because you're trying to use random.sample() on a set. In Python, random.sample() expects the population to be a sequence (like a list or tuple), not a set or dict. Sets are unordered and don't support indexing, which random.sample() relies on internally.
Here's how you can fix the error:
In your start_crawling function, locate the following line:
urls_to_crawl.update(random.sample(new_links, min(len(new_links), 100))) # Limit to 100 new URLs per page
Replace it with:
urls_to_crawl.update(random.sample(list(new_links), min(len(new_links), 100))) # Limit to 100 new URLs per page
Explanation:
- Convert
new_links, which is a set, into a list using list(new_links). This provides random.sample() with an indexable and ordered sequence.
Alternatively, you can sort the set (if ordering matters for your use case):
urls_to_crawl.update(random.sample(sorted(new_links), min(len(new_links), 100))) # Limit to 100 new URLs per page
Regarding the performance issue:
Your code is already using multithreading with ThreadPoolExecutor and 50 worker threads. However, there are several reasons why the crawler might still be slow:
-
Global Interpreter Lock (GIL):
- Python's GIL allows only one thread to execute Python bytecode at a time. This means that even with multithreading, CPU-bound tasks don't execute in true parallel.
- Since your code includes CPU-bound tasks (like
compute_rank with TfidfVectorizer), the GIL can become a bottleneck.
-
I/O Operations and Blocking:
- The
time.sleep() function in your crawl function causes threads to block, preventing them from doing other work.
- Database access with SQLite can be slow, especially when using locks and frequent connections/disconnections.
-
SQLite Limitations:
- SQLite, by default, doesn't handle concurrent writes well. Frequent writes from multiple threads can cause contention and slow down your program.
-
Per-Domain Throttling:
- You're introducing a
DOMAIN_DELAY of 1 second between requests to the same domain. With many URLs pointing to the same domain, this can significantly slow down the crawler.
Optimizations to improve speed:
-
Use Asynchronous Programming:
- Switch from multithreading to asynchronous I/O using
asyncio and aiohttp.
- Asynchronous code is more efficient for I/O-bound tasks, as it doesn't rely on threads and avoids the GIL limitations.
-
Modify Database Access:
-
Persistent Connections:
- Instead of opening and closing the database connection for each page, maintain a persistent connection per thread or use a connection pool.
- Example:
# At the start of your thread or worker
conn = sqlite3.connect('search_engine.db', check_same_thread=False)
cursor = conn.cursor()
# In your store_page function
def store_page(url, content, rank):
with db_lock:
cursor.execute("INSERT OR IGNORE INTO pages (url, content, rank) VALUES (?, ?, ?)", (url, content, rank))
conn.commit()
- Note: Ensure thread safety when sharing connections.
-
Batch Inserts:
- Collect multiple pages' data and insert them in batches to reduce the number of commits.
-
Switch Databases:
- Consider using a database designed for concurrent access (e.g., PostgreSQL or MongoDB).
-
Optimize compute_rank Function:
- Reuse the Vectorizer:
- Initialize
TfidfVectorizer once and reuse it.
- However,
TfidfVectorizer needs to be fitted on a corpus, so you might need to collect documents before fitting.
- Alternative Ranking Methods:
- Use simpler ranking methods that are less computationally intensive.
- Example: Use the length of the content or the number of keywords.
-
Reduce Lock Contention:
- Minimize the time locks are held.
- Use finer-grained locks or lock-free data structures when possible.
-
Adjust Throttling Strategy:
- Dynamic Delays:
- Implement dynamic delays based on the site's
Crawl-delay directive in robots.txt.
- If
robots.txt allows faster crawling, reduce the delay.
Implementing Asynchronous Programming with asyncio and aiohttp:
Here's how you might start to convert your crawler:
import asyncio
import aiohttp
from aiohttp import ClientSession
import time
async def can_fetch_async(url):
# Implement async version of can_fetch or adjust your current function
pass
async def crawl_async(url):
if not await can_fetch_async(url):
print(f"Disallowed by robots.txt: {url}")
return [], ""
parsed_url = urlparse(url)
domain = parsed_url.netloc
# Implement per-domain throttling without blocking
elapsed = time.time() - domain_access_times[domain]
if elapsed < DOMAIN_DELAY:
await asyncio.sleep(DOMAIN_DELAY - elapsed)
headers = {'User-Agent': USER_AGENT}
try:
async with ClientSession(headers=headers) as session:
async with session.get(url, timeout=10) as response:
domain_access_times[domain] = time.time()
if response.status != 200:
print(f"Failed to retrieve {url}: Status code {response.status}")
return [], ""
content = await response.text()
soup = BeautifulSoup(content, 'html.parser')
# Process content as before
# ...
return links, text
except Exception as e:
print(f"Error crawling {url}: {e}")
return [], ""
async def main(seed_urls, max_depth=2):
create_index()
visited = set()
urls_to_crawl = set(seed_urls)
for depth in range(max_depth):
print(f"Depth {depth+1}/{max_depth}")
tasks = []
current_level_urls = urls_to_crawl.copy()
urls_to_crawl.clear()
for url in current_level_urls:
if url not in visited:
visited.add(url)
tasks.append(crawl_and_store_async(url, visited))
results = await asyncio.gather(*tasks)
for links in results:
new_links = set(links) - visited
urls_to_crawl.update(random.sample(list(new_links), min(len(new_links), 100)))
random_url = get_random_url()
if random_url not in visited:
urls_to_crawl.add(random_url)
if __name__ == "__main__":
seed_urls = [ ... ] # Your list of seed URLs
asyncio.run(main(seed_urls, max_depth=3))
Note: Converting your entire codebase to use asyncio will require significant changes. You'll need to:
- Adjust all I/O operations to be asynchronous.
- Replace synchronous functions (like
requests.get) with asynchronous equivalents (aiohttp).
- Handle synchronization primitives (locks) appropriately in the asynchronous context.
- Ensure thread safety when accessing shared resources.
Additional Suggestions:
Final Notes:
- Be cautious when increasing the speed of your crawler to avoid overloading websites.
- Always respect
robots.txt and crawling policies.
- Consider limiting the number of concurrent connections to a single domain.
By addressing the TypeError and implementing the optimizations above, you should see a significant improvement in the speed of your crawler. Keep in mind that optimizing for speed must be balanced with ethical considerations and respect for the resources you're accessing.
Let me know if you have any questions or need further assistance!