write a webcrawler to crawl all articles including the plain text from the following…
- User
write a webcrawler to crawl all articles including the plain text from the following website: https://www.welt.de/
- Assistant
write a webcrawler to crawl all articles including the plain text from the following website: https://www.welt.de/
Creating a web crawler to scrape articles from a website like Welt involves several steps, including sending HTTP requests, parsing HTML content, and extracting the desired information. Below is an example of how you can create a simple web crawler using Python with the requests and BeautifulSoup libraries.
⚠️ Important Considerations:
Respect the Website’s Terms of Service: Before scraping any website, ensure that you have permission to do so by reviewing the site’s Terms of Service and robots.txt file (https://www.welt.de/robots.txt).
Rate Limiting: Be mindful of the load your crawler places on the website. Implement delays between requests to avoid overwhelming the server.
Legal and Ethical Use: Ensure that your scraping activities comply with all applicable laws and regulations, especially concerning copyright and data privacy.
Use Official APIs if Available: Sometimes websites offer official APIs for accessing their content, which is a preferred and more reliable method compared to web scraping.
Python 3.x: Ensure you have Python installed. You can download it from here.
Install Required Libraries: Install the necessary Python libraries using pip:
pip install requests
pip install beautifulsoup4
import requests
from bs4 import BeautifulSoup
import time
import csv
# Base URL of the website
BASE_URL = 'https://www.welt.de/'
# Headers to mimic a browser visit
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ' +
'AppleWebKit/537.36 (KHTML, like Gecko) ' +
'Chrome/58.0.3029.110 Safari/537.3'
}
def get_article_links(page_url):
"""
Fetches article links from the given page URL.
"""
response = requests.get(page_url, headers=HEADERS)
if response.status_code != 200:
print(f"Failed to retrieve page: {page_url}")
return []
soup = BeautifulSoup(response.text, 'html.parser')
links = []
# This selector may need to be updated based on the website's structure
for a_tag in soup.find_all('a', href=True):
href = a_tag['href']
if '/politik/' in href or '/wirtschaft/' in href or '/sport/' in href:
if href.startswith('/'):
full_url = BASE_URL.rstrip('/') + href
links.append(full_url)
elif href.startswith('https://www.welt.de/'):
links.append(href)
# Remove duplicates
return list(set(links))
def extract_article_text(article_url):
"""
Extracts the title and text from an article URL.
"""
response = requests.get(article_url, headers=HEADERS)
if response.status_code != 200:
print(f"Failed to retrieve article: {article_url}")
return None, None
soup = BeautifulSoup(response.text, 'html.parser')
# Extract the title
title_tag = soup.find('h1')
title = title_tag.get_text(strip=True) if title_tag else 'No Title'
# Extract the article text
article_body = soup.find('div', {'class': 'article__body'}) # Update based on actual site structure
paragraphs = article_body.find_all('p') if article_body else []
article_text = '\n'.join([para.get_text(strip=True) for para in paragraphs])
return title, article_text
def crawl_welt(start_url, max_pages=10, delay=1):
"""
Crawls the Welt website starting from the start_url.
"""
visited = set()
to_visit = [start_url]
articles = []
while to_visit and len(visited) < max_pages:
current_url = to_visit.pop(0)
if current_url in visited:
continue
print(f"Visiting: {current_url}")
visited.add(current_url)
links = get_article_links(current_url)
for link in links:
if link not in visited and link not in to_visit:
to_visit.append(link)
title, text = extract_article_text(current_url)
if title and text:
articles.append({'url': current_url, 'title': title, 'text': text})
print(f"Scraped: {title}")
time.sleep(delay) # Be polite and wait before the next request
return articles
def save_articles_to_csv(articles, filename='welt_articles.csv'):
"""
Saves the scraped articles to a CSV file.
"""
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['url', 'title', 'text']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for article in articles:
writer.writerow(article)
if __name__ == "__main__":
start_page = BASE_URL
scraped_articles = crawl_welt(start_page, max_pages=50, delay=2)
save_articles_to_csv(scraped_articles)
print(f"Scraped {len(scraped_articles)} articles.")
Imports:
requests: To send HTTP requests.BeautifulSoup from bs4: To parse HTML content.time: To implement delays between requests.csv: To save the scraped data.Headers:
Functions:
get_article_links: Fetches and parses the main page to extract article URLs. Adjust the URL patterns based on the website's structure and the sections you are interested in.
extract_article_text: Takes an article URL, fetches its content, and extracts the title and main text. The selectors ('h1' for the title and 'div', {'class': 'article__body'} for the article body) may need to be updated depending on the website's HTML structure.
crawl_welt: Manages the crawling process. It keeps track of visited URLs, limits the number of pages to crawl (max_pages), and adds a delay between requests to respect the server load.
save_articles_to_csv: Saves the extracted articles to a CSV file for further analysis or storage.
Main Execution:
welt_articles.csv.Adjust Selectors: Websites often update their HTML structure. Inspect the Welt website to find the correct HTML tags and classes for articles.
Pagination Handling: If you want to navigate through multiple pages or sections, you may need to implement additional logic to handle pagination.
Error Handling: Enhance error handling to manage exceptions and retries for failed requests.
Politeness (Robots.txt): Before scraping, check the robots.txt file to understand which parts of the website are allowed to be crawled. For Welt, you can view it here.
For more complex crawling tasks, consider using the Scrapy framework, which offers more advanced features like asynchronous requests, built-in support for handling various data exports, and better performance.
Installation:
pip install scrapy
Basic Scrapy Spider Example:
import scrapy
class WeltSpider(scrapy.Spider):
name = "welt"
start_urls = ['https://www.welt.de/']
def parse(self, response):
# Extract article links
for href in response.css('a::attr(href)').getall():
if '/politik/' in href or '/wirtschaft/' in href or '/sport/' in href:
if href.startswith('/'):
href = response.urljoin(href)
yield scrapy.Request(href, callback=self.parse_article)
# Follow pagination links if necessary
next_page = response.css('a.next::attr(href)').get()
if next_page:
yield response.follow(next_page, self.parse)
def parse_article(self, response):
title = response.css('h1::text').get()
paragraphs = response.css('div.article__body p::text').getall()
text = '\n'.join(paragraphs)
yield {
'url': response.url,
'title': title,
'text': text
}
Running the Spider:
Save the spider code in a file named welt_spider.py and run:
scrapy runspider welt_spider.py -o welt_articles.json
This command will save the scraped articles to a welt_articles.json file.
Maintenance: Websites frequently change their structure, so your crawler might require regular maintenance to keep it functional.
Ethical Scraping: Always prioritize ethical considerations and legality when scraping data. When in doubt, seek permission or consult legal expertise.
Performance: For large-scale scraping, consider optimizing your crawler for performance and scalability, possibly by using asynchronous requests or distributed crawling systems.
By following the above guidelines and customizing the crawler to fit the specific structure of Welt, you can effectively scrape and extract articles and their plain text content.
Not yet included in a published release.