Compare commits

..
3 Commits
Author SHA1 Message Date
hz4th_coder d23d526629 修复搜索和重复检查问题
1. 搜索文章时增加URL字段搜索,解决重复抓取问题
2. 优化搜索结果解析,多获取几个结果确保返回足够数量
2026-07-13 23:51:23 +08:00
hz4th_coder 24f0d3c35b 修复搜索抓取相关问题
1. 放宽搜索结果过滤条件,返回更多结果
2. 抓取返回详细错误信息(如超时、网络错误等)
3. 错误信息记录到失败URL库中
4. 统一返回格式包含success字段
2026-07-13 23:40:13 +08:00
hz4th_coder b0d98b78d9 修复停止按钮:搜索开始时即显示
- 搜索开始就显示停止按钮
- 搜索完成后隐藏,自动抓取时再显示
- 整个流程中都可以随时停止
2026-07-13 23:22:02 +08:00
4 changed files with 46 additions and 19 deletions
+4 -4
View File
@@ -157,16 +157,16 @@ class Database:
if category: if category:
cursor.execute(''' cursor.execute('''
SELECT * FROM articles SELECT * FROM articles
WHERE (product_names LIKE ? OR keywords LIKE ? OR summary LIKE ? OR content LIKE ?) WHERE (product_names LIKE ? OR keywords LIKE ? OR summary LIKE ? OR content LIKE ? OR url LIKE ?)
AND category = ? AND category = ?
ORDER BY fetch_date DESC ORDER BY fetch_date DESC
''', (f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', category)) ''', (f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', category))
else: else:
cursor.execute(''' cursor.execute('''
SELECT * FROM articles SELECT * FROM articles
WHERE product_names LIKE ? OR keywords LIKE ? OR summary LIKE ? OR content LIKE ? WHERE product_names LIKE ? OR keywords LIKE ? OR summary LIKE ? OR content LIKE ? OR url LIKE ?
ORDER BY fetch_date DESC ORDER BY fetch_date DESC
''', (f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', f'%{keyword}%')) ''', (f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', f'%{keyword}%', f'%{keyword}%'))
return [dict(row) for row in cursor.fetchall()] return [dict(row) for row in cursor.fetchall()]
def get_article_by_id(self, article_id): def get_article_by_id(self, article_id):
+3 -2
View File
@@ -114,7 +114,7 @@ def fetch_article():
result = search_service.fetch_url_content(url) result = search_service.fetch_url_content(url)
if result: if result and result.get('success'):
# 自动保存到内容库 # 自动保存到内容库
article_id = search_service.save_to_articles( article_id = search_service.save_to_articles(
product_names=data.get('product_names', [result['title']]), product_names=data.get('product_names', [result['title']]),
@@ -132,7 +132,8 @@ def fetch_article():
'data': result 'data': result
}) })
else: else:
return jsonify({'error': '抓取失败'}), 500 error_msg = result.get('error', '抓取失败') if result else '抓取失败'
return jsonify({'success': False, 'error': error_msg}), 500
@bp.route('/internet-search', methods=['POST']) @bp.route('/internet-search', methods=['POST'])
def internet_search(): def internet_search():
+21 -8
View File
@@ -151,18 +151,23 @@ class SearchService:
continue continue
# 匹配标题链接:link "标题文字" [ref=eXX] # 匹配标题链接:link "标题文字" [ref=eXX]
# 需要过滤域名链接(如 "zhihu.com")和短链接 # 过滤域名链接(如 "zhihu.com")和短链接
if 'link "' in line and '[ref=' in line: if 'link "' in line and '[ref=' in line:
match = re.search(r'link "([^"]+)" \[ref=(e\d+)\]', line) match = re.search(r'link "([^"]+)" \[ref=(e\d+)\]', line)
if match: if match:
title = match.group(1) title = match.group(1)
ref = match.group(2) ref = match.group(2)
# 过滤短标题(域名链接如 "zhihu.com" # 过滤纯域名格式
if len(title) > 20 and '.' not in title[:10]: # 不是域名格式 is_domain = (title.endswith('.com') or title.endswith('.cn') or
title.endswith('.net') or title.endswith('.org') or
title.endswith('.edu') or title.endswith('.gov'))
if not is_domain:
refs.append((title, ref)) refs.append((title, ref))
# 获取每个结果的 URL # 获取每个结果的 URL,多获取几个以防解析失败
for title, ref in refs[:max_results]: for title, ref in refs[:max_results + 5]:
if len(results) >= max_results:
break
url = self._get_link_url(ref) url = self._get_link_url(ref)
if url and 'bing.com/search' not in url: # 过滤搜索结果页本身的链接 if url and 'bing.com/search' not in url: # 过滤搜索结果页本身的链接
results.append({ results.append({
@@ -225,13 +230,18 @@ class SearchService:
def fetch_url_content(self, url): def fetch_url_content(self, url):
"""抓取网页内容(使用 agent-browser 浏览器方式,绕过反爬虫)""" """抓取网页内容(使用 agent-browser 浏览器方式,绕过反爬虫)"""
error_message = None
try: try:
# 使用浏览器方式抓取,增加超时时间到60秒 # 使用浏览器方式抓取,增加超时时间到60秒
stdout, stderr, code = self._run_browser('open', url, '--timeout', '60000') stdout, stderr, code = self._run_browser('open', url, '--timeout', '60000')
if code != 0: if code != 0:
error_message = stderr.strip() if stderr else '浏览器打开页面失败'
print(f"打开页面失败: {stderr}") print(f"打开页面失败: {stderr}")
# 浏览器失败,尝试使用 requests 备用方案 # 浏览器失败,尝试使用 requests 备用方案
return self._fetch_with_requests(url) result = self._fetch_with_requests(url)
if result:
return result
return {'success': False, 'error': error_message}
# 等待页面加载(增加到10秒) # 等待页面加载(增加到10秒)
self._run_browser('wait', '10000') self._run_browser('wait', '10000')
@@ -263,6 +273,7 @@ class SearchService:
description = text[:200].strip() if text else '' description = text[:200].strip() if text else ''
return { return {
'success': True,
'title': title, 'title': title,
'description': description, 'description': description,
'content': text, 'content': text,
@@ -270,13 +281,14 @@ class SearchService:
'fetch_date': datetime.now().isoformat() 'fetch_date': datetime.now().isoformat()
} }
except Exception as e: except Exception as e:
print(f"抓取URL失败: {url}, 错误: {str(e)}") error_message = str(e)
print(f"抓取URL失败: {url}, 错误: {error_message}")
# 尝试关闭浏览器 # 尝试关闭浏览器
try: try:
self._run_browser('close') self._run_browser('close')
except: except:
pass pass
return None return {'success': False, 'error': error_message}
def _extract_text_from_snapshot(self, snapshot): def _extract_text_from_snapshot(self, snapshot):
"""从 accessibility tree snapshot 中提取文本内容""" """从 accessibility tree snapshot 中提取文本内容"""
@@ -340,6 +352,7 @@ class SearchService:
description = text[:200].strip() if text else '' description = text[:200].strip() if text else ''
return { return {
'success': True,
'title': title, 'title': title,
'description': description, 'description': description,
'content': text, 'content': text,
+18 -5
View File
@@ -45,9 +45,11 @@ async function doSearch() {
updateStatus('searching', `正在通过 ${engineNames[engine]} 搜索...`); updateStatus('searching', `正在通过 ${engineNames[engine]} 搜索...`);
document.getElementById('search-btn').disabled = true; document.getElementById('search-btn').disabled = true;
// 显示进度 // 显示进度和停止按钮
shouldStop = false;
const progress = document.getElementById('search-progress'); const progress = document.getElementById('search-progress');
progress.style.display = 'block'; progress.style.display = 'block';
document.getElementById('stop-btn').style.display = 'inline-flex';
document.getElementById('progress-fill').style.width = '0%'; document.getElementById('progress-fill').style.width = '0%';
document.getElementById('progress-text').textContent = '正在搜索...'; document.getElementById('progress-text').textContent = '正在搜索...';
@@ -70,6 +72,14 @@ async function doSearch() {
displayResults(); displayResults();
// 检查是否被停止
if (shouldStop) {
document.getElementById('stop-btn').style.display = 'none';
document.getElementById('progress-text').textContent = '已停止';
updateStatus('warning', '搜索已停止');
return;
}
// 显示缓存状态 // 显示缓存状态
if (data.cached) { if (data.cached) {
updateStatus('success', `找到 ${searchResults.length} 条结果(使用缓存)`); updateStatus('success', `找到 ${searchResults.length} 条结果(使用缓存)`);
@@ -83,25 +93,28 @@ async function doSearch() {
document.getElementById('progress-fill').style.width = '100%'; document.getElementById('progress-fill').style.width = '100%';
document.getElementById('progress-text').textContent = '搜索完成!'; document.getElementById('progress-text').textContent = '搜索完成!';
document.getElementById('stop-btn').style.display = 'none'; // 隐藏停止按钮
// 自动抓取和保存 // 自动抓取和保存
if (autoFetch && searchResults.length > 0) { if (autoFetch && searchResults.length > 0) {
setTimeout(() => fetchAllResults(autoSave), 500); setTimeout(() => fetchAllResults(autoSave), 500);
} else {
setTimeout(() => {
progress.style.display = 'none';
}, 1000);
} }
} else { } else {
document.getElementById('stop-btn').style.display = 'none';
updateStatus('error', '搜索失败'); updateStatus('error', '搜索失败');
showToast('搜索失败: ' + data.error, 'error'); showToast('搜索失败: ' + data.error, 'error');
} }
} catch (error) { } catch (error) {
document.getElementById('stop-btn').style.display = 'none';
updateStatus('error', '搜索出错'); updateStatus('error', '搜索出错');
showToast('搜索出错', 'error'); showToast('搜索出错', 'error');
console.error(error); console.error(error);
} }
setTimeout(() => {
progress.style.display = 'none';
}, 1000);
document.getElementById('search-btn').disabled = false; document.getElementById('search-btn').disabled = false;
} }