使用 Trea cn 设计 爬虫程序 so esay

196 阅读5分钟

使用 Trea cn 设计 爬虫程序 so esay

在现代数据驱动的时代,网络爬虫已成为数据采集的重要工具。传统的爬虫开发往往需要处理复杂的HTTP请求、HTML解析、URL处理等技术细节。而借助 Trea CN 这样的AI辅助开发工具,我们可以更高效地构建功能完善的爬虫程序。

本文将通过实际案例,展示如何使用 Trea CN 快速开发一个遵循robots协议的Python网络爬虫。

环境准备:安装必要的依赖包

pip install requests beautifulsoup4 lxml html5lib

各包说明:

库名功能描述特点
requestsHTTP请求库简洁易用,功能强大
beautifulsoup4HTML/XML解析库语法直观,容错性强
lxml高性能XML/HTML解析器速度快,功能丰富
html5lib纯Python HTML5解析器解析最准确,但速度较慢

使用 Trea

trea 下载

写一个 simple_crawler_python.py 1添加函数,负责获取并解析网站的·robots协议提高了爬虫的合规性。 2.爬取 python.org 的网址· 3.网址导入到python.org.txt

image.png

代码

import requests
from bs4 import BeautifulSoup
from urllib.parse import urlparse, urljoin
import time

# 配置项
TARGET_URL = "https://www.python.org"
OUTPUT_FILE = "python.org.txt"
USER_AGENT = "SimpleCrawler/1.0 (+https://www.example.com)"


def check_robots_txt(url):
    """
    检查网站的robots.txt协议,判断是否允许爬取
    :param url: 目标网站URL
    :return: 是否允许爬取
    """
    parsed_url = urlparse(url)
    robots_url = urljoin(url, "/robots.txt")
    
    try:
        headers = {"User-Agent": USER_AGENT}
        response = requests.get(robots_url, headers=headers, timeout=10)
        
        if response.status_code == 200:
            print(f"成功获取robots.txt: {robots_url}")
            # 简单解析robots.txt,检查是否允许爬取
            # 实际应用中可能需要更复杂的解析
            disallow_all = False
            allow_user_agent = True
            
            for line in response.text.split("\n"):
                line = line.strip()
                if line.startswith("User-agent:"):
                    agent = line.split(":")[1].strip()
                    if agent == "*" or agent.lower() in USER_AGENT.lower():
                        allow_user_agent = True
                    else:
                        allow_user_agent = False
                elif line.startswith("Disallow:") and allow_user_agent:
                    path = line.split(":")[1].strip()
                    if path == "/":
                        disallow_all = True
                        break
            
            if disallow_all:
                print("robots.txt禁止爬取该网站")
                return False
            else:
                print("robots.txt允许爬取该网站")
                return True
        else:
            print(f"无法获取robots.txt,状态码: {response.status_code}")
            # 如果没有robots.txt,默认允许爬取
            return True
    except Exception as e:
        print(f"获取robots.txt时出错: {str(e)}")
        # 出错时默认允许爬取
        return True


def crawl_website(url):
    """
    爬取网站并提取所有链接
    :param url: 目标网站URL
    :return: 链接列表
    """
    links = []
    try:
        headers = {"User-Agent": USER_AGENT}
        response = requests.get(url, headers=headers, timeout=10)
        
        if response.status_code == 200:
            soup = BeautifulSoup(response.text, "html.parser")
            title = soup.title.string if soup.title else "无标题"
            print(f"成功爬取网站: {url}")
            print(f"网站标题: {title}")
            
            # 提取所有链接
            for a_tag in soup.find_all("a", href=True):
                href = a_tag["href"]
                # 转换为绝对路径
                absolute_url = urljoin(url, href)
                # 只保留当前域名的链接
                if urlparse(absolute_url).netloc == urlparse(url).netloc:
                    links.append(absolute_url)
            
            # 去重
            links = list(set(links))
            print(f"共找到 {len(links)} 个链接")
        else:
            print(f"爬取网站失败,状态码: {response.status_code}")
    except Exception as e:
        print(f"爬取网站时出错: {str(e)}")
    
    return links


def save_to_file(links, file_path):
    """
    将链接保存到文件
    :param links: 链接列表
    :param file_path: 输出文件路径
    """
    try:
        with open(file_path, "w", encoding="utf-8") as f:
            for link in links:
                f.write(link + "\n")
        print(f"链接已保存到: {file_path}")
    except Exception as e:
        print(f"保存链接时出错: {str(e)}")


def main():
    print(f"开始爬取: {TARGET_URL}")
    
    # 检查robots协议
    if not check_robots_txt(TARGET_URL):
        print("根据robots协议,取消爬取")
        return
    
    # 延迟一下,避免请求过快
    time.sleep(1)
    
    # 爬取网站
    links = crawl_website(TARGET_URL)
    
    # 保存链接
    if links:
        save_to_file(links, OUTPUT_FILE)
    
    print("爬取完成")


if __name__ == "__main__":
    main()

技术深度解析:urllib.parse 核心功能

1. urlparse() - URL解析神器

urlparse() 函数能够将复杂的URL分解成易于处理的组件:

from urllib.parse import urlparse

解析复杂URL

url = "https://www.python.org/downloads/release/python-3-11/?tab=source#files"
parsed = urlparse(url)

print(f"🌐 协议: {parsed.scheme}")      # https
print(f"🏠 域名: {parsed.netloc}")      # www.python.org  
print(f"📁 路径: {parsed.path}")        # /downloads/release/python-3-11/
print(f"⚙️  参数: {parsed.params}")      # (空)
print(f"🔍 查询: {parsed.query}")       # tab=source
print(f"📍 锚点: {parsed.fragment}")    # files

输出效果

🌐 协议: https
🏠 域名: www.python.org
📁 路径: /downloads/release/python-3-11/
⚙️ 参数: 
🔍 查询: tab=source
📍 锚点: files

2. urljoin() - URL智能拼接器

urljoin() 函数能够智能处理基础URL与相对路径的组合:

from urllib.parse import urljoin
base_url = "https://www.python.org/downloads/"

# 演示各种路径拼接场景
test_cases = [
    ("release/", "相对路径拼接"),
    ("/about/", "绝对路径拼接"), 
    ("../community/", "上级目录拼接"),
    ("https://docs.python.org/", "完整URL覆盖")
]

print("🔗 URL拼接示例:")
for path, description in test_cases:
    result = urljoin(base_url, path)
    print(f"  {description}: {path}{result}")

输出效果

🔗 URL拼接示例:
  相对路径拼接: release/ → https://www.python.org/downloads/release/
  绝对路径拼接: /about/ → https://www.python.org/about/
  上级目录拼接: ../community/ → https://www.python.org/community/
  完整URL覆盖: https://docs.python.org/ → https://docs.python.org/

实际应用场景

爬虫中的URL处理最佳实践

from urllib.parse import urlparse, urljoin

def normalize_and_validate_url(base_url, found_url):
    """
    标准化和验证URL
    :param base_url: 基础URL
    :param found_url: 发现的URL
    :return: 处理后的URL或None
    """
    # 使用urljoin处理相对路径
    full_url = urljoin(base_url, found_url)
    
    # 使用urlparse进行验证
    parsed = urlparse(full_url)
    
    # 验证URL合法性
    if not all([parsed.scheme, parsed.netloc]):
        return None
    
    # 只接受HTTP/HTTPS协议
    if parsed.scheme not in ['http', 'https']:
        return None
    
    # 移除锚点,避免重复爬取
    clean_url = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
    if parsed.query:
        clean_url += f"?{parsed.query}"
    
    return clean_url

# 使用示例
base = "https://www.python.org/about/"
test_urls = ["../downloads/", "mailto:admin@example.com", "javascript:void(0)", "/community/"]

for url in test_urls:
    result = normalize_and_validate_url(base, url)
    status = "✅ 有效" if result else "❌ 无效"
    print(f"{status}: {url}{result}")

总结与展望

通过本文的实践案例,我们看到了如何使用 Trea CN 高效开发一个功能完善的网络爬虫。主要收获包括:

✨ 核心优势

  • AI辅助开发:Trea CN 的智能提示大幅提升编码效率
  • 协议遵守:自动检查robots.txt,确保合规爬取
  • 错误处理:完善的异常处理机制,提高程序健壮性
  • 结果管理:智能化的数据提取和保存功能

🚀 技术要点

  • URL处理:urllib.parse 模块的灵活运用
  • 智能解析:BeautifulSoup的高效HTML解析
  • 友好爬取:合理的延迟机制和User-Agent设置
  • 日志记录:完整的运行状态监控

🔮 未来方向

  • 随着AI技术的发展,像Trea CN这样的智能开发工具将会:
  • 提供更精准的代码生成
  • 支持更复杂的业务逻辑自动化
  • 实现更智能的错误诊断和修复
  • 集成更多的开发生态工具