Please modify this code to work with Techpowerup, code: import requests from bs4 import…
- User
Please modify this code to work with Techpowerup, code: import requests from bs4 import BeautifulSoup import os from tqdm import tqdm
directory to save articles
dir_path = 'C:/Users/Dell-PC/Documents/Scraped-Data'
number of articles to scrape
num_articles = 100
Function to check internet connection
def check_internet_connection(url="http://www.google.com", timeout=30): try: _ = requests.get(url, timeout=timeout) return True except requests.ConnectionError: print("No internet connection available.") return False
Function to check if an article already exists
def article_exists(article_url): filename = os.path.join(dir_path, article_url.split('/')[-1] + '.txt') return os.path.exists(filename)
Create the directory if it doesn’t exist
os.makedirs(dir_path, exist_ok=True)
Make sure we have an internet connection before starting the scraping
if not check_internet_connection(): print("No internet connection available. Please check your connection and try again.") exit()
Counter for the number of articles downloaded
downloaded_articles = 10
Partial URL for Wikipedia articles
wikipedia_base_url = "https://en.wikipedia.org"
get full URL for the category page
category_url = wikipedia_base_url + "/wiki/Category_(mathematics)"
Start the scraping process
try: page = requests.get(category_url) page.raise_for_status() except requests.RequestException as e: print(f"An error occurred while requesting the page: {e}") exit()
parse page
soup = BeautifulSoup(page.content, 'html.parser')
find all article links
articles = soup.find_all('a', href=lambda href: href and href.startswith('/wiki/') and ':' not in href)
Limit the number of articles to the num_articles variable
articles = articles[:num_articles]
get full URLs
articles = [wikipedia_base_url + a['href'] for a in articles]
Create a progress bar
progress_bar = tqdm(total=num_articles, desc="Scraping Articles", unit="article")
loop through articles
for url in articles: if not check_internet_connection(): print("Lost internet connection during operation. Stopping the process.") break
code - Assistant