Trường Hợp Sử Dụng

Tổng hợp tin tức và phương tiện truyền thông bằng cách xử lý CAPTCHA

Các hãng tin tức và nền tảng truyền thông sử dụng CAPTCHA để bảo vệ nội dung khỏi việc tổng hợp tự động. Các nhà giám sát truyền thông, các công ty PR và các tổ chức nghiên cứu cần thu thập các bài báo theo chương trình. CaptchaAI xử lý các thử thách CAPTCHA trên nhiều nguồn tin tức.


CAPTCHA trên nền tảng tin tức

Loại nguồn CAPTCHA Trình kích hoạt Nội dung
Các hãng tin lớn Cloudflare Turnstile Phát hiện bot Bài viết, tiêu đề
Dịch vụ dây (AP, Reuters) reCAPTCHA v2 Truy cập hàng loạt Tin nóng hổi
Ấn phẩm có tường phí reCAPTCHA v3 nỗ lực truy cập Bài viết cao cấp
Các trang tin tức địa phương reCAPTCHA v2 Giới hạn tỷ lệ Tin tức khu vực
Tổng hợp tin tức Cloudflare Challenge Phát hiện cạo Nguồn cấp dữ liệu tổng hợp
Các trang thông cáo báo chí CAPTCHA hình ảnh Tải trang xuống nội dung PR

Tổng hợp tin tức

import requests
import time
import re
from bs4 import BeautifulSoup
from datetime import datetime
import json

CAPTCHAAI_KEY = "YOUR_API_KEY"
CAPTCHAAI_URL = "https://ocr.captchaai.com"

def solve_captcha(method, sitekey, pageurl, **kwargs):
    data = {
        "key": CAPTCHAAI_KEY, "method": method,
        "googlekey": sitekey, "pageurl": pageurl, "json": 1,
    }
    data.update(kwargs)
    resp = requests.post(f"{CAPTCHAAI_URL}/in.php", data=data)
    task_id = resp.json()["request"]
    for _ in range(60):
        time.sleep(5)
        result = requests.get(f"{CAPTCHAAI_URL}/res.php", params={
            "key": CAPTCHAAI_KEY, "action": "get",
            "id": task_id, "json": 1,
        })
        r = result.json()
        if r["request"] != "CAPCHA_NOT_READY":
            return r["request"]
    raise TimeoutError("Timeout")

class NewsAggregator:
    def __init__(self, proxy=None):
        self.session = requests.Session()
        if proxy:
            self.session.proxies = {"http": proxy, "https": proxy}
        self.session.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
            "AppleWebKit/537.36 Chrome/126.0.0.0 Safari/537.36",
            "Accept-Language": "en-US,en;q=0.9",
        })

    def collect_headlines(self, source_url, section=None):
        """Collect headlines from a news source."""
        url = f"{source_url}/{section}" if section else source_url
        resp = self.session.get(url, timeout=30)

        if self._has_captcha(resp.text):
            resp = self._solve_and_retry(resp.text, url)

        soup = BeautifulSoup(resp.text, "html.parser")
        articles = []

        for item in soup.select("article, .story, .headline-item, h2 a, h3 a"):
            link = item if item.name == "a" else item.select_one("a")
            if link:
                articles.append({
                    "title": link.get_text(strip=True),
                    "url": self._abs_url(source_url, link.get("href", "")),
                    "source": source_url,
                    "collected_at": datetime.now().isoformat(),
                })

        return articles

    def get_article(self, article_url):
        """Fetch full article content."""
        resp = self.session.get(article_url, timeout=30)

        if self._has_captcha(resp.text):
            resp = self._solve_and_retry(resp.text, article_url)

        soup = BeautifulSoup(resp.text, "html.parser")

        # Remove unwanted elements
        for tag in soup.select("script, style, nav, footer, .ad, .sidebar"):
            tag.decompose()

        content_el = soup.select_one(
            "article, .article-body, .story-body, .entry-content"
        )

        return {
            "url": article_url,
            "title": self._text(soup, "h1, .article-title"),
            "author": self._text(soup, ".author, .byline, [rel='author']"),
            "date": self._text(soup, "time, .publish-date, .article-date"),
            "content": content_el.get_text(separator="\n", strip=True) if content_el else "",
            "word_count": len(content_el.get_text().split()) if content_el else 0,
        }

    def aggregate_sources(self, sources, max_articles_per=20):
        """Aggregate headlines across multiple sources."""
        all_articles = []

        for source in sources:
            try:
                articles = self.collect_headlines(source["url"], source.get("section"))
                all_articles.extend(articles[:max_articles_per])
                print(f"{source['name']}: {len(articles)} headlines")
            except Exception as e:
                print(f"{source['name']}: Error - {e}")
            time.sleep(3)

        return all_articles

    def _has_captcha(self, html):
        return any(tag in html.lower() for tag in [
            'data-sitekey', 'g-recaptcha', 'cf-turnstile',
        ])

    def _solve_and_retry(self, html, url):
        match = re.search(r'data-sitekey="([^"]+)"', html)
        if not match:
            return self.session.get(url)
        sitekey = match.group(1)
        if 'cf-turnstile' in html:
            token = solve_captcha("turnstile", sitekey, url)
            return self.session.post(url, data={"cf-turnstile-response": token})
        token = solve_captcha("userrecaptcha", sitekey, url)
        return self.session.post(url, data={"g-recaptcha-response": token})

    def _text(self, soup, selector):
        el = soup.select_one(selector)
        return el.get_text(strip=True) if el else ""

    def _abs_url(self, base, href):
        if href.startswith("http"):
            return href
        return base.rstrip("/") + "/" + href.lstrip("/")

# Usage
aggregator = NewsAggregator(
    proxy="http://user:pass@residential.proxy.com:5000"
)

sources = [
    {"name": "Tech News A", "url": "https://technews-a.example.com", "section": "latest"},
    {"name": "Business B", "url": "https://business-b.example.com", "section": "tech"},
    {"name": "Industry C", "url": "https://industry-c.example.com"},
]

headlines = aggregator.aggregate_sources(sources)
print(f"Total: {len(headlines)} headlines collected")

Giám sát tin tức dựa trên từ khóa

class NewsMonitor:
    def __init__(self, keywords, sources, proxy=None):
        self.keywords = [kw.lower() for kw in keywords]
        self.aggregator = NewsAggregator(proxy=proxy)
        self.sources = sources
        self.seen_urls = set()

    def scan(self):
        """Scan for articles matching keywords."""
        headlines = self.aggregator.aggregate_sources(self.sources)
        matches = []

        for article in headlines:
            if article["url"] in self.seen_urls:
                continue

            title_lower = article["title"].lower()
            matched_kws = [kw for kw in self.keywords if kw in title_lower]

            if matched_kws:
                article["matched_keywords"] = matched_kws
                matches.append(article)
                self.seen_urls.add(article["url"])

        return matches

    def continuous_monitor(self, interval_min=30):
        """Run continuous monitoring with alerts."""
        while True:
            matches = self.scan()
            if matches:
                print(f"\n=== {len(matches)} new matches found ===")
                for m in matches:
                    print(f"  [{', '.join(m['matched_keywords'])}] {m['title']}")
                    print(f"    {m['url']}")
            else:
                print(f"No new matches at {datetime.now().strftime('%H:%M')}")

            time.sleep(interval_min * 60)

# Monitor for specific topics
monitor = NewsMonitor(
    keywords=["captcha", "bot detection", "web scraping", "automation"],
    sources=sources,
    proxy="http://user:pass@residential.proxy.com:5000",
)
matches = monitor.scan()

Kế hoạch ngân sách tên miền

  • Chỉ định ngân sách thu thập dữ liệu cho mỗi nguồn dựa trên nhu cầu làm mới, áp lực CAPTCHA và giá trị của luồng nội dung.
  • Trước tiên, hãy làm chậm các miền nhạy cảm thay vì áp dụng cùng một kiểu thử lại trên tất cả các nhà xuất bản.
  • Theo dõi các lần giải, bỏ sót và tìm nạp nhịp trên mỗi miền để có thể điều chỉnh ngân sách bằng các tín hiệu thực.

Khắc phục sự cố

Vấn đề Nguyên nhân Cách xử lý
Cloudflare chặn tất cả các yêu cầu Phát hiện bot tích cực Sử dụng đa dạng nguồn yêu cầu + UA thực tế
Tường phí thay vì bài viết Nội dung đằng sau đăng ký Phát hiện tường phí, bỏ qua hoặc xử lý
CAPTCHA trên mỗi trang IP được gắn cờ Xoay proxy, thêm độ trễ hơn 5 giây
Nội dung bài viết trống Nội dung được hiển thị bằng JS Sử dụng Selenium/Puppeteer cho các trang SPA
Bài viết trùng lặp Cùng một câu chuyện từ nhiều nguồn Loại bỏ trùng lặp theo tiêu đề tương tự

Câu hỏi thường gặp

Tổng hợp tin tức có hợp pháp không?

Thu thập tiêu đề và siêu dữ liệu để nghiên cứu hoặc theo dõi là thông lệ. Sao chép đầy đủ các bài viết có bản quyền mà không được phép. Sử dụng đoạn trích và liên kết trở lại nguồn ban đầu.

Làm cách nào để xử lý nội dung có tường phí?

Phát hiện tường phí (tìm các lớp CSS của tường phí hoặc độ dài nội dung giới hạn) và gắn cờ cho tường phí đó. Chỉ truy cập nội dung bạn được phép xem.

Loại proxy nào hoạt động tốt nhất cho các trang tin tức?

Các đa dạng nguồn yêu cầu luân phiên hoạt động tốt nhất. Các hãng tin tức lớn sử dụng Cloudflare, công cụ chặn mạnh mẽ các IP của trung tâm dữ liệu.


Hướng dẫn liên quan

  • Ủy quyền dân cư luân phiên
  • Nghiên cứu truyền thông xã hội

Tin tức tổng hợp từ mọi nguồn —lấy khóa CaptchaAI của bạnvà tự động hóa việc thu thập nội dung.

Os comentários estão desativados para este artigo.