Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,7 @@ import markdownify
|
|
| 4 |
import readabilipy.simple_json
|
| 5 |
from urllib.parse import urlparse, urlunparse
|
| 6 |
from protego import Protego
|
| 7 |
-
from typing import Tuple
|
| 8 |
|
| 9 |
# 定义用户代理
|
| 10 |
DEFAULT_USER_AGENT = "Gradio Fetch App/1.0 (https://gradio.app)"
|
|
@@ -12,25 +12,21 @@ DEFAULT_USER_AGENT = "Gradio Fetch App/1.0 (https://gradio.app)"
|
|
| 12 |
# --- 核心功能函数 (未改变) ---
|
| 13 |
# ... (extract_content_from_html, get_robots_txt_url, check_can_fetch 函数保持不变) ...
|
| 14 |
def extract_content_from_html(html: str) -> str:
|
| 15 |
-
"""从HTML中提取主要内容并转换为Markdown。"""
|
| 16 |
try:
|
| 17 |
ret = readabilipy.simple_json.simple_json_from_html_string(html, use_readability=True)
|
| 18 |
if not ret or not ret.get("content"):
|
| 19 |
return "页面简化失败:无法从HTML中提取主要内容。"
|
| 20 |
-
|
| 21 |
content = markdownify.markdownify(ret["content"], heading_style=markdownify.ATX)
|
| 22 |
return content if content.strip() else "页面简化后内容为空。"
|
| 23 |
except Exception as e:
|
| 24 |
return f"处理HTML时出错: {e}"
|
| 25 |
|
| 26 |
def get_robots_txt_url(url: str) -> str:
|
| 27 |
-
"""根据给定的URL获取robots.txt的地址。"""
|
| 28 |
parsed = urlparse(url)
|
| 29 |
robots_url = urlunparse((parsed.scheme, parsed.netloc, "/robots.txt", "", "", ""))
|
| 30 |
return robots_url
|
| 31 |
|
| 32 |
def check_can_fetch(url: str, user_agent: str) -> Tuple[bool, str]:
|
| 33 |
-
"""检查 robots.txt 是否允许抓取。返回一个元组 (是否允许, 消息)。"""
|
| 34 |
robots_url = get_robots_txt_url(url)
|
| 35 |
try:
|
| 36 |
response = requests.get(robots_url, headers={"User-Agent": user_agent}, timeout=5)
|
|
@@ -43,51 +39,54 @@ def check_can_fetch(url: str, user_agent: str) -> Tuple[bool, str]:
|
|
| 43 |
except requests.exceptions.RequestException as e:
|
| 44 |
return True, f"检查 {robots_url} 时发生网络错误: {e},将继续尝试抓取。"
|
| 45 |
|
| 46 |
-
|
| 47 |
-
# --- 主处理函数 (已添加详细描述) ---
|
| 48 |
def fetch_and_process_url(
|
| 49 |
-
url:
|
| 50 |
-
ignore_robots:
|
| 51 |
-
force_raw:
|
| 52 |
-
max_length:
|
| 53 |
-
start_index:
|
| 54 |
) -> str:
|
| 55 |
-
"""
|
| 56 |
-
抓取并处理指定URL的网页内容。
|
| 57 |
|
| 58 |
此函数会访问一个网页,智能地提取其主要正文内容,并将其转换为简洁的Markdown格式。
|
| 59 |
它还能处理robots.txt规则、内容截断和返回原始HTML等高级功能。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
"""
|
| 61 |
if not url or not url.strip().startswith(('http://', 'https://')):
|
| 62 |
return "请输入一个有效的URL (以 http:// 或 https:// 开头)。"
|
| 63 |
|
|
|
|
| 64 |
url = url.strip()
|
| 65 |
user_agent = DEFAULT_USER_AGENT
|
| 66 |
-
|
| 67 |
if not ignore_robots:
|
| 68 |
can_fetch, message = check_can_fetch(url, user_agent)
|
| 69 |
if not can_fetch:
|
| 70 |
return message
|
| 71 |
-
|
| 72 |
try:
|
| 73 |
response = requests.get(url, headers={"User-Agent": user_agent}, timeout=30, allow_redirects=True)
|
| 74 |
response.raise_for_status()
|
| 75 |
except requests.exceptions.RequestException as e:
|
| 76 |
return f"抓取URL时发生网络错误: {e}"
|
| 77 |
-
|
| 78 |
page_raw = response.text
|
| 79 |
content_type = response.headers.get("content-type", "").lower()
|
| 80 |
-
|
| 81 |
is_html = "text/html" in content_type
|
| 82 |
prefix = ""
|
| 83 |
-
|
| 84 |
if is_html and not force_raw:
|
| 85 |
content = extract_content_from_html(page_raw)
|
| 86 |
else:
|
| 87 |
content = page_raw
|
| 88 |
if not is_html:
|
| 89 |
prefix = f"**注意**: 内容类型是 `{content_type}`,已显示为原始内容。\n\n---\n\n"
|
| 90 |
-
|
| 91 |
original_length = len(content)
|
| 92 |
if start_index >= original_length:
|
| 93 |
content_to_show = "错误:起始索引超出了内容总长度。"
|
|
@@ -104,18 +103,16 @@ def fetch_and_process_url(
|
|
| 104 |
f"要获取更多内容,请将**起始索引**设置为 **{next_start}** 再试。"
|
| 105 |
)
|
| 106 |
content_to_show += truncation_message
|
| 107 |
-
|
| 108 |
return prefix + content_to_show
|
| 109 |
|
|
|
|
| 110 |
# --- Gradio 界面定义 (未改变) ---
|
| 111 |
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 112 |
gr.Markdown("# 网页内容抓取与简化工具")
|
| 113 |
gr.Markdown("输入一个网址,工具会抓取其内容,并默认提取正文转换为Markdown格式。")
|
| 114 |
-
|
| 115 |
with gr.Row():
|
| 116 |
url_input = gr.Textbox(label="URL", placeholder="例如: https://www.google.com/about", scale=4)
|
| 117 |
fetch_button = gr.Button("抓取内容", variant="primary", scale=1)
|
| 118 |
-
|
| 119 |
with gr.Accordion("高级选项", open=False):
|
| 120 |
with gr.Row():
|
| 121 |
ignore_robots_checkbox = gr.Checkbox(label="忽略 robots.txt 限制", value=False)
|
|
@@ -123,9 +120,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
|
|
| 123 |
with gr.Row():
|
| 124 |
max_length_slider = gr.Slider(minimum=500, maximum=50000, value=8000, step=500, label="返回内容的最大长度 (字符数)")
|
| 125 |
start_index_number = gr.Number(label="起始索引", value=0)
|
| 126 |
-
|
| 127 |
output_markdown = gr.Markdown(label="抓取结果")
|
| 128 |
-
|
| 129 |
fetch_button.click(
|
| 130 |
fn=fetch_and_process_url,
|
| 131 |
inputs=[url_input, ignore_robots_checkbox, raw_checkbox, max_length_slider, start_index_number],
|
|
@@ -133,5 +128,4 @@ with gr.Blocks(theme=gr.themes.Soft()) as app:
|
|
| 133 |
)
|
| 134 |
|
| 135 |
if __name__ == "__main__":
|
| 136 |
-
# 启动时加上 mcp_server=True
|
| 137 |
app.launch(mcp_server=True)
|
|
|
|
| 4 |
import readabilipy.simple_json
|
| 5 |
from urllib.parse import urlparse, urlunparse
|
| 6 |
from protego import Protego
|
| 7 |
+
from typing import Tuple
|
| 8 |
|
| 9 |
# 定义用户代理
|
| 10 |
DEFAULT_USER_AGENT = "Gradio Fetch App/1.0 (https://gradio.app)"
|
|
|
|
| 12 |
# --- 核心功能函数 (未改变) ---
|
| 13 |
# ... (extract_content_from_html, get_robots_txt_url, check_can_fetch 函数保持不变) ...
|
| 14 |
def extract_content_from_html(html: str) -> str:
|
|
|
|
| 15 |
try:
|
| 16 |
ret = readabilipy.simple_json.simple_json_from_html_string(html, use_readability=True)
|
| 17 |
if not ret or not ret.get("content"):
|
| 18 |
return "页面简化失败:无法从HTML中提取主要内容。"
|
|
|
|
| 19 |
content = markdownify.markdownify(ret["content"], heading_style=markdownify.ATX)
|
| 20 |
return content if content.strip() else "页面简化后内容为空。"
|
| 21 |
except Exception as e:
|
| 22 |
return f"处理HTML时出错: {e}"
|
| 23 |
|
| 24 |
def get_robots_txt_url(url: str) -> str:
|
|
|
|
| 25 |
parsed = urlparse(url)
|
| 26 |
robots_url = urlunparse((parsed.scheme, parsed.netloc, "/robots.txt", "", "", ""))
|
| 27 |
return robots_url
|
| 28 |
|
| 29 |
def check_can_fetch(url: str, user_agent: str) -> Tuple[bool, str]:
|
|
|
|
| 30 |
robots_url = get_robots_txt_url(url)
|
| 31 |
try:
|
| 32 |
response = requests.get(robots_url, headers={"User-Agent": user_agent}, timeout=5)
|
|
|
|
| 39 |
except requests.exceptions.RequestException as e:
|
| 40 |
return True, f"检查 {robots_url} 时发生网络错误: {e},将继续尝试抓取。"
|
| 41 |
|
| 42 |
+
# --- 主处理函数 (使用 Google 风格 Docstring) ---
|
|
|
|
| 43 |
def fetch_and_process_url(
|
| 44 |
+
url: str,
|
| 45 |
+
ignore_robots: bool,
|
| 46 |
+
force_raw: bool,
|
| 47 |
+
max_length: int,
|
| 48 |
+
start_index: int
|
| 49 |
) -> str:
|
| 50 |
+
"""抓取并处理指定URL的网页内容。
|
|
|
|
| 51 |
|
| 52 |
此函数会访问一个网页,智能地提取其主要正文内容,并将其转换为简洁的Markdown格式。
|
| 53 |
它还能处理robots.txt规则、内容截断和返回原始HTML等高级功能。
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
url (str): 需要抓取的完整网址,必须以 http:// 或 https:// 开头。
|
| 57 |
+
ignore_robots (bool): 是否忽略目标网站的 robots.txt 文件中的抓取限制。
|
| 58 |
+
force_raw (bool): 是否返回未经简化的原始HTML内容,而不是提取后的Markdown文本。
|
| 59 |
+
max_length (int): 返回内容的最大字符数。用于处理超长页面。
|
| 60 |
+
start_index (int): 从内容的哪个字符位置开始返回。用于分页获取超长内容。
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
str: 处理后的网页内容或错误信息。
|
| 64 |
"""
|
| 65 |
if not url or not url.strip().startswith(('http://', 'https://')):
|
| 66 |
return "请输入一个有效的URL (以 http:// 或 https:// 开头)。"
|
| 67 |
|
| 68 |
+
# ... 函数的其余部分代码保持不变 ...
|
| 69 |
url = url.strip()
|
| 70 |
user_agent = DEFAULT_USER_AGENT
|
|
|
|
| 71 |
if not ignore_robots:
|
| 72 |
can_fetch, message = check_can_fetch(url, user_agent)
|
| 73 |
if not can_fetch:
|
| 74 |
return message
|
|
|
|
| 75 |
try:
|
| 76 |
response = requests.get(url, headers={"User-Agent": user_agent}, timeout=30, allow_redirects=True)
|
| 77 |
response.raise_for_status()
|
| 78 |
except requests.exceptions.RequestException as e:
|
| 79 |
return f"抓取URL时发生网络错误: {e}"
|
|
|
|
| 80 |
page_raw = response.text
|
| 81 |
content_type = response.headers.get("content-type", "").lower()
|
|
|
|
| 82 |
is_html = "text/html" in content_type
|
| 83 |
prefix = ""
|
|
|
|
| 84 |
if is_html and not force_raw:
|
| 85 |
content = extract_content_from_html(page_raw)
|
| 86 |
else:
|
| 87 |
content = page_raw
|
| 88 |
if not is_html:
|
| 89 |
prefix = f"**注意**: 内容类型是 `{content_type}`,已显示为原始内容。\n\n---\n\n"
|
|
|
|
| 90 |
original_length = len(content)
|
| 91 |
if start_index >= original_length:
|
| 92 |
content_to_show = "错误:起始索引超出了内容总长度。"
|
|
|
|
| 103 |
f"要获取更多内容,请将**起始索引**设置为 **{next_start}** 再试。"
|
| 104 |
)
|
| 105 |
content_to_show += truncation_message
|
|
|
|
| 106 |
return prefix + content_to_show
|
| 107 |
|
| 108 |
+
|
| 109 |
# --- Gradio 界面定义 (未改变) ---
|
| 110 |
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 111 |
gr.Markdown("# 网页内容抓取与简化工具")
|
| 112 |
gr.Markdown("输入一个网址,工具会抓取其内容,并默认提取正文转换为Markdown格式。")
|
|
|
|
| 113 |
with gr.Row():
|
| 114 |
url_input = gr.Textbox(label="URL", placeholder="例如: https://www.google.com/about", scale=4)
|
| 115 |
fetch_button = gr.Button("抓取内容", variant="primary", scale=1)
|
|
|
|
| 116 |
with gr.Accordion("高级选项", open=False):
|
| 117 |
with gr.Row():
|
| 118 |
ignore_robots_checkbox = gr.Checkbox(label="忽略 robots.txt 限制", value=False)
|
|
|
|
| 120 |
with gr.Row():
|
| 121 |
max_length_slider = gr.Slider(minimum=500, maximum=50000, value=8000, step=500, label="返回内容的最大长度 (字符数)")
|
| 122 |
start_index_number = gr.Number(label="起始索引", value=0)
|
|
|
|
| 123 |
output_markdown = gr.Markdown(label="抓取结果")
|
|
|
|
| 124 |
fetch_button.click(
|
| 125 |
fn=fetch_and_process_url,
|
| 126 |
inputs=[url_input, ignore_robots_checkbox, raw_checkbox, max_length_slider, start_index_number],
|
|
|
|
| 128 |
)
|
| 129 |
|
| 130 |
if __name__ == "__main__":
|
|
|
|
| 131 |
app.launch(mcp_server=True)
|