Ví dụ Thực tế
Cập nhật lần cuối:
Thảo luậnMục lục
Phần này cung cấp các ví dụ thực tế về cách sử dụng thư viện vnstock_news để giải quyết các tác vụ thu thập dữ liệu phổ biến, từ việc lấy tin tức từ các nguồn đã cấu hình sẵn đến việc xử lý các Sitemap hoặc RSS feeds tùy ý.
5.1. Lấy tin tức từ trang đã cấu hình sẵn
Đây là cách sử dụng cơ bản nhất, tận dụng các cấu hình đã có trong vnstock_news/config/sites.py.
Python
from vnstock_news.core.crawler import Crawler
import pandas as pd
# Khởi tạo Crawler cho trang CafeF
crawler_cafef = Crawler(site_name='cafef')
# Lấy 5 bài viết mới nhất (metadata) từ CafeF
# Crawler sẽ tự động sử dụng RSS hoặc Sitemap đã cấu hình cho CafeF
article_metadata = crawler_cafef.get_articles(limit=5)
if article_metadata:
print("5 bài viết mới nhất từ CafeF:")
for meta in article_metadata:
print(f"- {meta.get('title', 'N/A')} ({meta.get('url', 'N/A')})")
# Lấy chi tiết bài viết đầu tiên
first_article_url = article_metadata[0]['url']
print(f"\nĐang lấy chi tiết bài viết: {first_article_url}")
detailed_article = crawler_cafef.get_article_details(first_article_url)
if detailed_article:
print(f"Tiêu đề: {detailed_article.get('title')}")
print(f"Nội dung (trích đoạn): {detailed_article.get('markdown_content', '')[:150]}...")
else:
print("Không tìm thấy bài viết nào từ CafeF.")5.2. Lấy tin tức từ Sitemap hoặc RSS bất kỳ
Bạn có thể sử dụng Crawler để lấy tin tức từ một Sitemap hoặc RSS feed bất kỳ, ngay cả khi nó không phải là nguồn mặc định của một trang đã cấu hình sẵn. Điều quan trọng là phải cung cấp site_name phù hợp để Crawler biết cách phân tích nội dung bài viết.
Python
from vnstock_news.core.crawler import Crawler
from vnstock_news.core.rss import RSS # Cần import RSS nếu bạn muốn fetch RSS feed trực tiếp
import pandas as pd
# --- Ví dụ 1: Lấy từ Sitemap bất kỳ (ví dụ: sitemap của The Saigon Times) ---
# Chọn một site_name có cấu hình parser phù hợp với cấu trúc bài viết trên sitemap này.
# 'ktsg' là lựa chọn tốt vì nó thuộc cùng domain.
ktsg_sitemap_url = "https://thesaigontimes.vn/post-sitemap.xml"
print(f"\n--- Lấy bài viết từ Sitemap bất kỳ: {ktsg_sitemap_url} ---")
try:
crawler_ktsg = Crawler(site_name='ktsg')
article_metadata_list = crawler_ktsg.get_articles(sitemap_url=ktsg_sitemap_url, limit=3)
if article_metadata_list:
print(f"Tìm thấy {len(article_metadata_list)} URL. Đang lấy chi tiết...")
detailed_articles = []
for meta in article_metadata_list:
url = meta.get('url')
if url:
try:
details = crawler_ktsg.get_article_details(url)
detailed_articles.append(details)
except Exception as e:
print(f" Lỗi khi lấy chi tiết bài viết {url}: {e}")
if detailed_articles:
df_sitemap = pd.DataFrame(detailed_articles)
print("Bài viết chi tiết từ Sitemap:")
print(df_sitemap[['title', 'url', 'publish_time']].head())
else:
print("Không tìm thấy URL bài viết nào trong sitemap.")
except Exception as e:
print(f"Lỗi xảy ra khi lấy từ sitemap: {e}")
# --- Ví dụ 2: Lấy từ RSS bất kỳ (ví dụ: RSS của Báo Đầu Tư) ---
# Tương tự, chọn một site_name có cấu hình parser phù hợp.
baodautu_rss_url = "https://baodautu.vn/rss/tin-moi-nhat.rss"
print(f"\n--- Lấy bài viết từ RSS bất kỳ: {baodautu_rss_url} ---")
try:
# Bước 1: Dùng lớp RSS để lấy các mục từ RSS feed
rss_parser = RSS(rss_url=baodautu_rss_url, description_format='text')
rss_items = rss_parser.fetch()
if rss_items:
print(f"Tìm thấy {len(rss_items)} mục RSS. Đang lấy chi tiết...")
# Khởi tạo Crawler với site_name 'baodautu' để có cấu hình parser phù hợp
crawler_baodautu = Crawler(site_name='baodautu')
# Bước 2: Lấy chi tiết từng bài viết từ các URL trong RSS feed
detailed_articles_from_rss = []
for item in rss_items:
url = item.get('link') # Các mục RSS thường dùng 'link' cho URL
if url:
try:
details = crawler_baodautu.get_article_details(url)
detailed_articles_from_rss.append(details)
except Exception as e:
print(f" Lỗi khi lấy chi tiết bài viết {url}: {e}")
if detailed_articles_from_rss:
df_rss = pd.DataFrame(detailed_articles_from_rss)
print("Bài viết chi tiết từ RSS:")
print(df_rss[['title', 'url', 'publish_time']].head())
else:
print("Không tìm thấy mục nào trong RSS feed.")
except Exception as e:
print(f"Lỗi xảy ra khi lấy từ RSS: {e}")5.3. Thu thập tin tức hàng loạt với BatchCrawler
Khi bạn cần thu thập chi tiết của một lượng lớn bài viết, BatchCrawler là công cụ hiệu quả để quản lý các yêu cầu và độ trễ.
Python
from vnstock_news.core.crawler import Crawler
from vnstock_news.core.batch import BatchCrawler
import pandas as pd
# Bước 1: Lấy danh sách URL từ một nguồn (ví dụ: VnExpress RSS)
crawler_vnexpress = Crawler(site_name='vnexpress')
article_metadata = crawler_vnexpress.get_articles(limit=10) # Lấy 10 URL
if article_metadata:
urls_to_batch_fetch = [item['url'] for item in article_metadata]
print(f"\n--- Đang thu thập hàng loạt {len(urls_to_batch_fetch)} bài viết từ VnExpress ---")
# Bước 2: Khởi tạo BatchCrawler và thực hiện thu thập
# Đặt request_delay để tránh bị chặn IP
batch_crawler = BatchCrawler(site_name='vnexpress', request_delay=0.5)
detailed_articles_df = batch_crawler.fetch_articles(sitemap_url=urls_to_batch_fetch)
if not detailed_articles_df.empty:
print("\nKết quả thu thập hàng loạt (5 dòng đầu):")
print(detailed_articles_df[['title', 'url', 'publish_time']].head())
else:
print("Không thu thập được bài viết nào trong lô.")
else:
print("Không có URL nào để thu thập hàng loạt.")
Thảo luận