顾乔芝士网

持续更新的前后端开发技术栈

实践cline+r1+claude 这种 deepclaude 自动编程思想

#每天学python##deepseek##vscode##自动编程#

如何使用:

vscode里安装cline最新插件,在cline插件里plan调用deepseekR1模型,act调用Claude模型。

在 plan 里提需求:

使用 cline 里的的 fetch 这个 mcpserver,用 python 语言,实现把一个网页里的正文,转换成 md 格式,然后输出到一个新建的 md 文件里。要求是程序运行时要求用户输入 url。

plan 会产生计划并让你决定是否实施

R1生成的计划:

1. 当前是PLAN MODE,需要先制定计划并与用户讨论

2. 任务要求:

使用fetch-mcp服务器获取网页内容

使用Python实现

将网页正文转换为markdown格式

输出到新建的md文件

运行时要求用户输入URL

3. 需要确认的细节:

输出md文件的路径和命名规则

是否需要处理网页中的图片、链接等元素

是否需要特定的markdown格式要求

4. 计划步骤:

使用fetch-mcp的fetch_markdown工具获取网页markdown

编写Python脚本处理用户输入和文件输出

创建新的md文件并写入转换后的内容

R1 提出的实施建议:

我建议按照以下步骤实现这个网页转markdown工具:

1. 使用fetch-mcp服务器的fetch_markdown工具获取网页内容

2. 编写Python脚本实现以下功能:

提示用户输入URL

调用fetch_markdown工具获取markdown内容

将内容写入新的markdown文件

3. 文件输出方案:

默认输出到当前目录

文件名使用网页标题或当前时间戳

文件扩展名为.md

确认后到 act 调用 claude 模型自动编写python 代码,然后根据提示一步一步调整优化,直到代码跑通。

下面是完整的python代码:

import json
import requests
from datetime import datetime
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import re

def clean_url(url):
    """Clean and validate URL."""
    # Remove control characters and extra whitespace
    url = ''.join(char for char in url if ord(char) >= 32).strip()
    
    # If multiple URLs are present, take the first complete one
    if url.count('http') > 1:
        # Find all occurrences of http:// or https://
        starts = [i for i in range(len(url)) if url.startswith(('http://', 'https://'), i)]
        if starts:
            # Take the first URL by finding the next occurrence or end of string
            start = starts[0]
            next_start = starts[1] if len(starts) > 1 else len(url)
            url = url[start:next_start].strip()
    
    # Add https:// if no protocol is specified
    if not url.startswith(('http://', 'https://')):
        url = 'https://' + url
    
    return url

def get_url():
    """Get URL input from user."""
    while True:
        url = input("Please enter the webpage URL: ").strip()
        if url:
            try:
                url = clean_url(url)
                return url
            except Exception as e:
                print(f"Error processing URL: {str(e)}")
                continue
        print("URL cannot be empty. Please try again.")

def fetch_markdown(url):
    """Fetch webpage content and convert to markdown."""
    try:
        # Fetch webpage content
        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'
        }
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        
        # Parse HTML content
        soup = BeautifulSoup(response.content, 'html.parser')
        
        # Remove unwanted elements
        for tag in soup(['script', 'style', 'nav', 'footer', 'iframe']):
            tag.decompose()
        
        # Get title
        title = soup.title.string if soup.title else "Untitled"
        content = [f"# {title.strip()}\n"]
        
        # Get main content
        main_content = soup.find('article') or soup.find('main') or soup.find('body')
        
        # Process paragraphs and headers
        for element in main_content.find_all(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']):
            text = element.get_text().strip()
            if text:
                if element.name.startswith('h'):
                    level = int(element.name[1])
                    content.append(f"\n{'#' * level} {text}\n")
                else:
                    content.append(f"\n{text}\n")
        
        return '\n'.join(content)
    except Exception as e:
        print(f"Error: {str(e)}")
        return None

def generate_filename(url):
    """Generate a filename based on URL and timestamp."""
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    domain = urlparse(url).netloc
    return f"{domain}_{timestamp}.md"

def main():
    # Get URL from user
    url = get_url()
    
    # Fetch markdown content
    print("Fetching content...")
    content = fetch_markdown(url)
    
    if content:
        # Generate filename
        filename = generate_filename(url)
        
        # Write content to file
        try:
            with open(filename, 'w', encoding='utf-8') as f:
                f.write(content)
            print(f"\nSuccess! Content saved to: {filename}")
        except Exception as e:
            print(f"Error saving file: {str(e)}")
    else:
        print("Failed to fetch content from the URL.")

if __name__ == "__main__":
    main()
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言