Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

The script is working but it is just leaving some conent of some news articles to be…

  1. User

    The script is working but it is just leaving some conent of some news articles to be blank :import requests from bs4 import BeautifulSoup import pandas as pd import datetime import time import logging import sys

    ------------------------ Configuration ------------------------

    Set up logging

    logging.basicConfig( filename='Output/scrape_air_news.log', level=logging.INFO, format='%(asctime)s:%(levelname)s:%(message)s' )

    Maximum number of consecutive skips before stopping the scraper

    Not needed now since we stop immediately on first mismatch

    MAX_CONSECUTIVE_SKIPS = 3

    ------------------------ Functions ------------------------

    def get_soup(url): """ Fetches the HTML content of a given URL and returns a BeautifulSoup object. """ try: 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' ) } response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() return BeautifulSoup(response.text, 'html.parser') except requests.exceptions.RequestException as e: logging.error(f"Error fetching URL {url}: {e}") print(f"Error fetching URL {url}: {e}") return None

    def scrape_article_content(article_url): """ Scrapes the full content from an individual article page. Returns the content as a string. """ soup = get_soup(article_url) if not soup: return 'No Content'

    # Extract Content
    content_div = soup.find('div', class_='entry-content')
    if content_div:
        paragraphs = content_div.find_all('p')
        # Join all paragraphs into a single string
        content = '\n'.join([para.get_text(strip=True) for para in paragraphs])
        return content
    else:
        logging.warning(f"No content found in article {article_url}")
        print(f"Warning: No content found in article {article_url}")
        return 'No Content'
    

    def parse_date(date_text): """ Parses the date string from the category page and returns it in 'YYYY-MM-DD' format. """ try: # Expected format: 'November 7, 2024 11:12 AM' date = datetime.datetime.strptime(date_text, '%B %d, %Y %I:%M %p') formatted_date = date.strftime('%Y-%m-%d') # Format: 'YYYY-MM-DD' return formatted_date except ValueError: logging.warning(f"Date format unexpected: '{date_text}'") print(f"Warning: Date format unexpected: '{date_text}'") return 'Unknown'

    def scrape_category_page(category_url, target_date): """ Scrapes all articles from a single category page that match the target date. Returns a tuple: (list of matching articles, bool indicating if scraping should continue) """ soup = get_soup(category_url) if not soup: return ([], False)

    articles = []
    
    # Find all article entries
    # Assuming each article is within a <h2 class="entry-title"><a href="...">Title</a></h2>
    article_titles = soup.find_all('h2', class_='entry-title')
    if not article_titles:
        logging.info(f"No articles found on page: {category_url}")
        print(f"No articles found on page: {category_url}")
        return (articles, False)
    
    # Iterate through each article entry
    for idx, entry in enumerate(article_titles):
        try:
            a_tag = entry.find('a')
            if a_tag and a_tag.has_attr('href'):
                title = a_tag.get_text(strip=True)
                link = a_tag['href']
    
                # Extract corresponding date
                # Assume the date <p> tag is a sibling or within the same parent
                # Find the next <p> tag with the specific class
                date_p = entry.find_next_sibling('p', class_='mb-0 colorPrimary fs-14')
                if not date_p:
                    # If not found as direct sibling, search within the same parent
                    parent = entry.parent
                    date_p = parent.find('p', class_='mb-0 colorPrimary fs-14')
    
                if date_p:
                    date_text = date_p.get_text(strip=True)
                    formatted_date = parse_date(date_text)
                    print(f"\nScraping article: {title} | URL: {link}")
                    logging.info(f"Scraping article: {title} | URL: {link}")
                    logging.info(f"Extracted date: {formatted_date}")
    
                    if formatted_date == target_date:
                        # Scrape full content from article page
                        content = scrape_article_content(link)
                        articles.append({
                            'Title': title,
                            'Link': link,
                            'Date': formatted_date,
                            'Content': content
                        })
                        logging.info(f"Article matches target date: {formatted_date} | Title: {title}")
                        print(f"--> Article matches target date: {formatted_date} | Title: {title}")
                    else:
                        # Date mismatch found; stop scraping
                        logging.info(f"Article skipped (date {formatted_date} does not match target date {target_date}). | Title: {title}")
                        print(f"--> Article skipped (date {formatted_date} does not match target date {target_date}). | Title: {title}")
                        return (articles, False)
                else:
                    logging.warning(f"No date found for article '{title}' on page {category_url}")
                    print(f"Warning: No date found for article '{title}' on page {category_url}")
                    # Depending on policy, you can choose to continue or stop scraping
                    # Here, we'll skip this article and continue
                    continue
    
                time.sleep(1)  # Polite delay between article requests
            else:
                logging.warning("Article entry without a valid link.")
                print("Warning: Article entry without a valid link.")
        except Exception as e:
            logging.error(f"Error processing article index {idx} on page {category_url}: {e}")
            print(f"Error processing article index {idx} on page {category_url}: {e}")
            continue  # Continue with the next article
    
    # If all articles on the page matched, continue scraping next page
    return (articles, True)
    

    def scrape_all_pages(base_category_url, target_date): """ Iterates through all paginated category pages and scrapes articles matching the target date. Stops paginating when a date mismatch is encountered. """ all_articles = [] page_number = 1

    while True:
        if page_number == 1:
            page_url = base_category_url
        else:
            page_url = f"{base_category_url}page/{page_number}/"
    
        logging.info(f"Scraping category page: {page_url}")
        print(f"\nScraping category page: {page_url}")
    
        articles, should_continue = scrape_category_page(page_url, target_date)
        all_articles.extend(articles)
    
        if not should_continue:
            logging.info(f"Stopping scraper after processing page {page_number}.")
            print(f"Stopping scraper after processing page {page_number}.")
            break
    
        page_number += 1
        time.sleep(2)  # Polite delay between category pages
    
    return all_articles
    

    def save_to_excel(articles, filename): """ Saves the list of articles to an Excel file. """ if not articles: logging.warning("No articles to save.") print("No articles to save.") return

    df = pd.DataFrame(articles)
    try:
        df.to_excel(filename, index=False)
        logging.info(f"Successfully saved {len(df)} articles to {filename}")
        print(f"Successfully saved {len(df)} articles to {filename}")
    except Exception as e:
        logging.error(f"Error saving to Excel: {e}")
        print(f"Error saving to Excel: {e}")
    

    ------------------------ Main Execution ------------------------

    if name == "main": # -------------------- Target Date Configuration -------------------- # Allow setting the target date via command-line argument for flexibility if len(sys.argv) > 1: input_date = sys.argv[1] try: # Validate the input date format datetime.datetime.strptime(input_date, '%Y-%m-%d') TARGET_DATE = input_date except ValueError: logging.error(f"Invalid date format provided: '{input_date}'. Use 'YYYY-MM-DD'.") print("Invalid date format. Please use 'YYYY-MM-DD'.") sys.exit(1) else: # Default to the current date TARGET_DATE = datetime.date.today().strftime('%Y-%m-%d') # e.g., '2024-11-07'

    # -------------------- Categories Configuration --------------------
    categories = ['national', 'international', 'business', 'sports']  # Added multiple categories
    
    # Base URL pattern for categories
    BASE_URL_PATTERN = 'https://www.newsonair.gov.in/category/{}/'  # Modified to include category placeholder
    
    # -------------------- Start Scraping --------------------
    start_time = time.time()
    logging.info(f"Starting scraper for date: {TARGET_DATE}")
    print(f"\nStarting scraper for date: {TARGET_DATE}")
    
    for category in categories:
        # Construct the base category URL
        BASE_CATEGORY_URL = BASE_URL_PATTERN.format(category)
    
        # Define the output Excel file name for each category
        OUTPUT_FILE = f'Output/air_news_{category}_{TARGET_DATE}.xlsx'  # Modified to include category in filename
    
        logging.info(f"Processing category: {category}")
        print(f"\nProcessing category: {category}")
    
        # Scrape all pages for the current category
        all_scraped_articles = scrape_all_pages(BASE_CATEGORY_URL, TARGET_DATE)
    
        # Save the scraped articles to Excel
        save_to_excel(all_scraped_articles, OUTPUT_FILE)
    
    end_time = time.time()
    total_time = end_time - start_time
    logging.info(f"Scraping completed in {total_time:.2f} seconds.")
    print(f"\nScraping completed in {total_time:.2f} seconds.")
    
  2. Assistant

    It sounds like your web scraper is successfully fetching articles but occasionally fails to extract the content, resulting in blank or 'No Content' entries. This issue typically arises when the scraper's assumptions about the website's HTML structure don't hold for all articles. Here's a comprehensive approach to diagnose and resolve this problem:

    1. Understand the Root Cause

    Before making changes, it's crucial to identify why some articles lack content:

    • HTML Structure Variations: Not all articles may use the same HTML structure or CSS classes. Some might use different containers or tags for their content.

    • Dynamic Content Loading: If some content is loaded dynamically via JavaScript, requests and BeautifulSoup might not capture it.

    • Access Restrictions: Certain articles might have restricted access or require additional headers/cookies.

    • Different Content Types: Some articles might contain multimedia content (videos, images) instead of or in addition to text.

    2. Enhance Logging for Better Insights

    To better understand which articles are missing content and why, enhance your logging to capture more details:

    def scrape_article_content(article_url):
        """
        Scrapes the full content from an individual article page.
        Returns the content as a string.
        """
        soup = get_soup(article_url)
        if not soup:
            return 'No Content'
    
        # List of possible container classes that might hold the article content
        possible_content_classes = ['entry-content', 'post-content', 'article-content', 'content']
    
        content = None
        for cls in possible_content_classes:
            content_div = soup.find('div', class_=cls)
            if content_div:
                paragraphs = content_div.find_all('p')
                if paragraphs:
                    content = '\n'.join([para.get_text(strip=True) for para in paragraphs])
                    break  # Stop searching once content is found
    
        if content:
            return content
        else:
            # As a fallback, try extracting all <p> tags in the page
            paragraphs = soup.find_all('p')
            if paragraphs:
                content = '\n'.join([para.get_text(strip=True) for para in paragraphs])
                logging.warning(f"Used fallback method for content extraction in article {article_url}")
                print(f"Warning: Used fallback method for content extraction in article {article_url}")
                return content
            else:
                logging.warning(f"No content found in article {article_url}")
                print(f"Warning: No content found in article {article_url}")
                return 'No Content'
    

    Explanation of Changes:

    • Multiple Content Classes: The possible_content_classes list includes alternative class names that the website might use for article content. Adjust this list based on the actual classes used on the site.

    • Fallback Mechanism: If none of the specified classes contain the content, the scraper attempts to extract all <p> tags from the page as a last resort. This approach can sometimes capture the main content, especially on pages with consistent paragraph usage.

    • Enhanced Logging: Logs a warning when the fallback method is used, helping you identify which articles require further attention.

    3. Inspect the Problematic Articles

    Identify which articles have 'No Content' and manually inspect their URLs:

    1. Collect URLs with 'No Content':

      Modify your scraping function to print or log URLs where content extraction fails.

      if content == 'No Content':
          logging.error(f"Failed to extract content for article: {article_url}")
          print(f"Error: Failed to extract content for article: {article_url}")
      
    2. Visit These URLs Manually:

      Open the problematic article URLs in your browser to inspect their HTML structure. Look for differences compared to successful articles, such as:

      • Different container tags or classes.
      • Content loaded via JavaScript.
      • Presence of multimedia elements without accompanying text.

    4. Handle JavaScript-Rendered Content

    If you discover that some articles load content dynamically using JavaScript, requests and BeautifulSoup won't capture this content. To handle such cases, consider using a headless browser like Selenium or Playwright. Here's a basic example using Selenium:

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service
    from selenium.webdriver.chrome.options import Options
    from bs4 import BeautifulSoup
    
    def get_soup_with_selenium(url):
        """
        Fetches the HTML content of a given URL using Selenium and returns a BeautifulSoup object.
        """
        try:
            chrome_options = Options()
            chrome_options.add_argument('--headless')  # Run in headless mode
            chrome_options.add_argument('--disable-gpu')
            chrome_options.add_argument('--no-sandbox')
    
            # Update the path to the ChromeDriver as needed
            service = Service('/path/to/chromedriver')
            driver = webdriver.Chrome(service=service, options=chrome_options)
    
            driver.get(url)
            time.sleep(3)  # Adjust sleep time as needed for the page to load
    
            html = driver.page_source
            driver.quit()
            return BeautifulSoup(html, 'html.parser')
        except Exception as e:
            logging.error(f"Selenium error fetching URL {url}: {e}")
            print(f"Selenium error fetching URL {url}: {e}")
            return None
    

    Integration:

    Modify the scrape_article_content function to try Selenium if BeautifulSoup fails:

    def scrape_article_content(article_url):
        """
        Scrapes the full content from an individual article page.
        Returns the content as a string.
        """
        soup = get_soup(article_url)
        if not soup:
            # Attempt with Selenium
            soup = get_soup_with_selenium(article_url)
            if not soup:
                return 'No Content'
    
        # Proceed with content extraction as before
        # ...
    

    Notes:

    • Performance Considerations: Using Selenium can significantly slow down your scraper. Use it only for articles where BeautifulSoup fails to extract content.

    • ChromeDriver Setup: Ensure that you have the appropriate version of ChromeDriver installed and that its path is correctly specified in the Service.

    5. Flexible Content Extraction Strategy

    Instead of relying solely on specific classes, use more flexible strategies to locate content:

    • Identify Main Content Area: Often, the main content is within a specific <main>, <article>, or similar semantic tag.

    • Use Content Density: Extract the section with the highest number of <p> tags or text content, assuming it's the main article body.

    Example:

    def scrape_article_content(article_url):
        """
        Scrapes the full content from an individual article page.
        Returns the content as a string.
        """
        soup = get_soup(article_url)
        if not soup:
            return 'No Content'
    
        # Attempt to find the main content area
        main_content = soup.find('main') or soup.find('article') or soup.find('div', class_=lambda x: x and 'content' in x.lower())
    
        if main_content:
            paragraphs = main_content.find_all('p')
            if paragraphs:
                content = '\n'.join([para.get_text(strip=True) for para in paragraphs])
                return content
    
        # Fallback to all <p> tags
        paragraphs = soup.find_all('p')
        if paragraphs:
            content = '\n'.join([para.get_text(strip=True) for para in paragraphs])
            logging.warning(f"Used fallback method for content extraction in article {article_url}")
            print(f"Warning: Used fallback method for content extraction in article {article_url}")
            return content
    
        logging.warning(f"No content found in article {article_url}")
        print(f"Warning: No content found in article {article_url}")
        return 'No Content'
    

    6. Implement Retry Mechanism

    Sometimes, network glitches or temporary issues might prevent successful content extraction. Implement a retry mechanism:

    from requests.adapters import HTTPAdapter
    from requests.packages.urllib3.util.retry import Retry
    
    def get_soup(url, retries=3, backoff_factor=0.3):
        """
        Fetches the HTML content of a given URL and returns a BeautifulSoup object.
        Implements retries for transient errors.
        """
        session = requests.Session()
        retry = Retry(
            total=retries,
            read=retries,
            connect=retries,
            backoff_factor=backoff_factor,
            status_forcelist=(500, 502, 504)
        )
        adapter = HTTPAdapter(max_retries=retry)
        session.mount('http://', adapter)
        session.mount('https://', adapter)
    
        try:
            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'
                )
            }
            response = session.get(url, headers=headers, timeout=10)
            response.raise_for_status()
            return BeautifulSoup(response.text, 'html.parser')
        except requests.exceptions.RequestException as e:
            logging.error(f"Error fetching URL {url}: {e}")
            print(f"Error fetching URL {url}: {e}")
            return None
    

    Benefits:

    • Resilience: Automatically retries transient failures like network hiccups.

    • Customization: Adjust retries and backoff_factor based on your requirements.

    7. Final Revised scrape_article_content Function

    Combining all the suggestions, here's the enhanced scrape_article_content function:

    def scrape_article_content(article_url):
        """
        Scrapes the full content from an individual article page.
        Returns the content as a string.
        """
        soup = get_soup(article_url)
        if not soup:
            # Attempt with Selenium if necessary
            soup = get_soup_with_selenium(article_url)
            if not soup:
                return 'No Content'
    
        # Define possible content containers
        possible_content_selectors = [
            {'name': 'div', 'class_': 'entry-content'},
            {'name': 'div', 'class_': 'post-content'},
            {'name': 'div', 'class_': 'article-content'},
            {'name': 'div', 'class_': 'content'},
            {'name': 'article'},
            {'name': 'main'},
        ]
    
        content = None
        for selector in possible_content_selectors:
            content_div = soup.find(selector['name'], class_=selector.get('class_'))
            if content_div:
                paragraphs = content_div.find_all('p')
                if paragraphs:
                    content = '\n'.join([para.get_text(strip=True) for para in paragraphs])
                    break  # Content found, exit loop
    
        if not content:
            # Fallback to all <p> tags in the main sections
            potential_main = soup.find('main') or soup.find('article')
            if potential_main:
                paragraphs = potential_main.find_all('p')
                if paragraphs:
                    content = '\n'.join([para.get_text(strip=True) for para in paragraphs])
                    logging.warning(f"Used fallback method for content extraction in article {article_url}")
                    print(f"Warning: Used fallback method for content extraction in article {article_url}")
        
        if not content:
            # Final fallback to all <p> tags
            paragraphs = soup.find_all('p')
            if paragraphs:
                content = '\n'.join([para.get_text(strip=True) for para in paragraphs])
                logging.warning(f"Used all <p> tags for content extraction in article {article_url}")
                print(f"Warning: Used all <p> tags for content extraction in article {article_url}")
        
        if content:
            return content
        else:
            logging.warning(f"No content found in article {article_url}")
            print(f"Warning: No content found in article {article_url}")
            return 'No Content'
    

    8. Additional Recommendations

    • Respect Robots.txt and Terms of Service: Ensure that your scraping activities comply with the website’s robots.txt and terms of service. Excessive scraping can lead to IP bans.

    • Use Proxies if Necessary: If you encounter IP blocking, consider using proxies or rotating IPs to distribute your requests.

    • Handle Rate Limiting: Adjust your time.sleep delays appropriately to avoid overwhelming the server.

    • Monitor and Update Selectors Regularly: Websites frequently update their structures. Regularly monitor and update your scraping logic to adapt to such changes.

    9. Testing the Enhanced Scraper

    After implementing the above changes:

    1. Run the Scraper on a Subset of Articles:

      Test the scraper on a limited number of articles, especially those previously resulting in 'No Content'.

    2. Verify the Output:

      Check the Excel output to ensure that the 'Content' field is now populated correctly.

    3. Iterate as Needed:

      If certain articles still lack content, inspect their HTML structure and adjust your scraper accordingly.

    10. Sample Logging Output

    With enhanced logging, you’ll receive detailed logs indicating the scraper’s progress and any issues encountered:

    2024-04-27 10:00:00,000:INFO:Scraping article: Sample Title | URL: https://www.newsonair.gov.in/sample-article
    2024-04-27 10:00:01,000:INFO:Extracted date: 2024-04-26
    2024-04-27 10:00:01,500:WARNING:Used fallback method for content extraction in article https://www.newsonair.gov.in/sample-article
    2024-04-27 10:00:01,500:INFO:Article matches target date: 2024-04-26 | Title: Sample Title
    

    This structured logging will help you trace the scraper’s behavior and quickly identify any remaining issues.

    11. Conclusion

    By making your scraper more flexible and robust in handling different HTML structures, implementing fallback mechanisms, and enhancing logging, you can significantly reduce the instances of missing content. Regular maintenance and monitoring will ensure that your scraper adapts to any future changes on the target website.

    If you continue to face issues or need further assistance, feel free to provide specific examples or URLs where the scraper fails to extract content, and I can offer more targeted guidance.