Skip to main content

A python library for parsing news articles

Project description

Malaysian News Parser

Python Version License Build Status

The Malaysian News Parser, is a python library for extracting and parsing news articles from multiple publishers. It supports both static and dynamic content parsing using BeautifulSoup and Selenium. This parser was developed with a focus on Malaysian news publishers, but this may work with other news organizations provided it is allowed.

Parser Dev Logo

Table of Contents

Installation

You can install the library using pip

pip install parser_dev

Usage

Initializing the Config Manager

Before using the library, you need to initialize the `PublisherConfigManager`:

This can be done by importing the manager from `publisher_configs`, and then initializing an instance of the manager

from parser_dev.publisher_config import PublisherConfigManager # Import Manager

# Initialize Manager instance
config_manager = PublisherConfigManager()

This was set as a global variable in the usage tests

Adding a Publisher

There are slight format differences between setting the publisher configuration for static and dynamic sites.

Static Publisher Config Format:

static_publisher_config = {
    'type': 'static', # For static, set this to static
    'headers': { # Only present for website types that are static. Omitted for Dynamic
        'header_name': 'header_value'
    },
    'body_selector': { # Article Body Selector info for beautiful soup
        'type': 'class, id, css'
        'element': '<div>, <article>, etc..., not required for css selector',
        'text': 'selector_text'
    },
    'date_selector': { # Article Date Selector info for beautiful soup
        'type': 'class, id, css',
        'element': '<div>, <article>, etc..., not required for css selector',
        'text': 'selector_text'
    },
    'author_selector': { # Article Author Selector info for beautiful soup
        'type': 'class, id, css',
        'element': '<div>, <article>, etc..., not required for css selector',
        'text': 'selector_text'
    }
}

Dynamic Publisher Config Format:

# Headers omitted, chrome_path and sleep_time added.
dynamic_publisher_config = {
    'type': 'dynamic', # For dynamic, set this to dynamic
    'chrome_path': os.getenv('CHROME_PATH') # your path to your Selenium compatible webdriver (set in your .env file)
        'body_selector': { # Article Body Selector info for beautiful soup
        'type': 'class, id, css'
        'element': '<div>, <article>, etc..., not required for css selector',
        'text': 'selector_text'
    },
    'date_selector': { # Article Date Selector info for beautiful soup
        'type': 'class, id, css',
        'element': '<div>, <article>, etc..., not required for css selector',
        'text': 'selector_text'
    },
    'author_selector': { # Article Author Selector info for beautiful soup
        'type': 'class, id, css',
        'element': '<div>, <article>, etc..., not required for css selector',
        'text': 'selector_text'
    },
    'sleep_time': 10, # set how long the webdriver should wait to render page, dtype: int
}

To add a new publisher configuration:

from parser_dev.publisher_config import PublisherConfigManager # Import Manager

# Initialize Manager instance
config_manager = PublisherConfigManager()

# desired new publisher configuration
new_publisher_config = {
    'type': 'static',
    'headers': {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
        'Accept-Language': 'en-US,en;q=0.9',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Connection': 'keep-alive',
        'Upgrade-Insecure-Requests': '1',
    },
    'body_selector': {
        'type': 'css',
        'element': 'div',
        'text': '#new-body-selector',
    },
    'date_selector': {
        'type': 'css',
        'element': 'div',
        'text': '#new-date-selector',
    }
}

config_manager.add_publisher('new_publisher', new_publisher_config)

Updating a Publisher

To update an existing publisher configuration:

update_publisher_config = {
    'body_selector': {
        'type': 'css',
        'text': 'body > main > section > div > div > div > section > div:nth-of-type(1) > strong',
    }
}

config_manager.update_publisher('new_publisher', update_publisher_config)

Remove a Publisher

To remove a publisher configuration:

config_manager.remove_publisher('new_publisher')

Retrieving Article Data

The existing publisher config names

Publisher Name in Config
Astro Awani astro_awani
Malay Mail malay_mail
Star star
Sun Daily sun_daily
FMT (Free Malaysia Today) fmt
Sinar Harian sinar_harian
Berita Harian berita_harian
Roti Kaya roti_kaya
New Straits Times nst
The Vibes the_vibes
World of Buzz world_of_buzz
Bernama bernama
Cili Sos cili_sos
Coconuts coconuts
The Edge the_edge
HMetro hmetro
Malaysian Gazette malaysia_gazette
Harakah Daily harakah_daily
Borneo Post borneo_post

To retrieve article data from a given URL:

from parser_dev import get_parser

# url of article
url = 'https://www.astroawani.com/berita-malaysia/pelajar-cemerlang-spm-dijamin-tempat-matrikulasi-atau-program-kpt-kpm-477101'

# publisher name
publisher_name = 'astro_awani'

# Get appropriate parser
parser = get_parser(publisher_name)

# Extract and parse article data
article_data = parser.get_article_data(url)

if article_data:
    print(f"Title: {article_data['title']}")
    print(f"Author: {article_data['author']}")
    print(f"Date: {article_data['date']}")
    print(f"Body: {article_data['body'][:1000]}")  # Print the first 1000 characters to keep it concise
else:
    print("Failed to fetch or parse article data.")

Testing

To run the tests, navigate to the project directory and use `unittest`:

python -m unittest discover -s src/tests

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the Repository
  2. Create a new branch: `git checkout -b feature/your-feature-name
  3. Make your changes and commit them: `git commit -m 'Add some feature'
  4. Push to the branch: `git push origin feature/your-feature-name`
  5. Submit a pull request.

Please make sure to update tests as appropriate.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

malaysian_news_parser-0.1.1.tar.gz (11.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

malaysian_news_parser-0.1.1-py3-none-any.whl (11.0 kB view details)

Uploaded Python 3

File details

Details for the file malaysian_news_parser-0.1.1.tar.gz.

File metadata

  • Download URL: malaysian_news_parser-0.1.1.tar.gz
  • Upload date:
  • Size: 11.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.11.3

File hashes

Hashes for malaysian_news_parser-0.1.1.tar.gz
Algorithm Hash digest
SHA256 b4ef0cfc1892ef41c8bf42ce3f36565c27261b6d25d2be814f49bb50797c5520
MD5 675416f3b251220bd802ccb34d03b2f4
BLAKE2b-256 81beee39b5eb373cb3e784a5eca894f2fb4c525ad78b6572a12b9e7dc6d9c1fb

See more details on using hashes here.

File details

Details for the file malaysian_news_parser-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for malaysian_news_parser-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d6696ca87b863be5a4fb188175e41274df16495f6d4c2b4a2d2182f17b792815
MD5 7443c8e7a29c685416e7a08d9dde638b
BLAKE2b-256 c125450026e0e89ee40ab227d62b182629fb7e77d535047a483dad078e69d18e

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page