-
Notifications
You must be signed in to change notification settings - Fork 4
feat: integrate FxZhihu implementation #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
apps/api/src/services/scrapers/zhihu/content_processing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| from urllib.parse import urlparse, parse_qs, unquote | ||
|
|
||
| from bs4 import BeautifulSoup | ||
|
|
||
|
|
||
| def fix_images_and_links(html: str) -> str: | ||
| """ | ||
| Port of FxZhihu's fixImagesAndLinks: | ||
| - Replace data-actualsrc with src on img tags | ||
| - Remove <u> tags preserving text content | ||
| """ | ||
| soup = BeautifulSoup(html, "html.parser") | ||
| for img in soup.find_all("img"): | ||
| actualsrc = img.get("data-actualsrc") | ||
| if actualsrc: | ||
| img["src"] = actualsrc | ||
| del img["data-actualsrc"] | ||
| for u_tag in soup.find_all("u"): | ||
| u_tag.unwrap() | ||
| return str(soup) | ||
|
|
||
|
|
||
| def extract_references(html: str) -> str: | ||
| """ | ||
| Port of FxZhihu's extractReference: | ||
| - Find <sup> tags with data-text, data-url, data-numero | ||
| - Return formatted reference list HTML | ||
| """ | ||
| soup = BeautifulSoup(html, "html.parser") | ||
| references = {} | ||
| for sup in soup.find_all("sup"): | ||
| text = sup.get("data-text") | ||
| url = sup.get("data-url", "") | ||
| numero = sup.get("data-numero") | ||
| if text and numero: | ||
| references[numero] = {"text": text, "url": url} | ||
| if not references: | ||
| return "" | ||
| sorted_refs = sorted(references.items(), key=lambda x: int(x[0])) | ||
| items = [] | ||
| for index, ref in sorted_refs: | ||
| url_html = f'<a href="{ref["url"]}">{ref["url"]}</a>' if ref["url"] else "" | ||
| items.append(f"<li>{ref['text']}{url_html}</li>") | ||
| return f'<hr><section><h2>参考</h2><ol>{"".join(items)}</ol></section>' | ||
|
|
||
|
|
||
| def unmask_zhihu_links(html: str) -> str: | ||
| """ | ||
| Port of FxZhihu's link unmasking: | ||
| - Decode https://link.zhihu.com/?target=... to actual URLs | ||
| """ | ||
| soup = BeautifulSoup(html, "html.parser") | ||
| for a_tag in soup.find_all("a", href=True): | ||
| href = a_tag["href"] | ||
| if href.startswith("https://link.zhihu.com/"): | ||
| try: | ||
| parsed = urlparse(href) | ||
| qs = parse_qs(parsed.query) | ||
| target = qs.get("target", [None])[0] | ||
| if target: | ||
| a_tag["href"] = unquote(target) | ||
| except Exception: | ||
| pass | ||
| return str(soup) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,58 @@ | ||
| import sys | ||
| import os | ||
|
|
||
| # Import content_processing directly to avoid pulling in the full zhihu scraper | ||
| # which has heavy dependencies (fastfetchbot_shared, httpx, etc.) | ||
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "apps", "api", "src", "services", "scrapers", "zhihu")) | ||
| from content_processing import ( | ||
| fix_images_and_links, | ||
| extract_references, | ||
| unmask_zhihu_links, | ||
| ) | ||
|
|
||
|
|
||
| def test_fix_images_replaces_data_actualsrc(): | ||
| html = '<img src="placeholder.jpg" data-actualsrc="https://real.jpg">' | ||
| result = fix_images_and_links(html) | ||
| assert 'src="https://real.jpg"' in result | ||
| assert "data-actualsrc" not in result | ||
|
|
||
|
|
||
| def test_fix_images_preserves_normal_src(): | ||
| html = '<img src="https://normal.jpg">' | ||
| result = fix_images_and_links(html) | ||
| assert 'src="https://normal.jpg"' in result | ||
|
|
||
|
|
||
| def test_fix_images_removes_u_tags(): | ||
| html = "<p>Hello <u>world</u></p>" | ||
| result = fix_images_and_links(html) | ||
| assert "<u>" not in result | ||
| assert "world" in result | ||
|
|
||
|
|
||
| def test_extract_references_with_refs(): | ||
| html = '<p>Text<sup data-text="Ref 1" data-url="https://example.com" data-numero="1">[1]</sup></p>' | ||
| result = extract_references(html) | ||
| assert "参考" in result | ||
| assert "Ref 1" in result | ||
| assert "https://example.com" in result | ||
|
|
||
|
|
||
| def test_extract_references_empty(): | ||
| html = "<p>No references here</p>" | ||
| result = extract_references(html) | ||
| assert result == "" | ||
|
|
||
|
|
||
| def test_unmask_zhihu_links(): | ||
| html = '<a href="https://link.zhihu.com/?target=https%3A%2F%2Fexample.com">link</a>' | ||
| result = unmask_zhihu_links(html) | ||
| assert "https://example.com" in result | ||
| assert "link.zhihu.com" not in result | ||
|
|
||
|
|
||
| def test_unmask_preserves_normal_links(): | ||
| html = '<a href="https://example.com">link</a>' | ||
| result = unmask_zhihu_links(html) | ||
| assert 'href="https://example.com"' in result |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consider logging failed URL unmasking attempts.
The silent
except: passmakes debugging difficult when URL parsing fails unexpectedly. Per coding guidelines, Loguru should be used for logging. Consider logging at debug level to aid troubleshooting without cluttering normal output.🛠️ Proposed fix
+from fastfetchbot_shared.utils.logger import logger from urllib.parse import urlparse, parse_qs, unquotetry: parsed = urlparse(href) qs = parse_qs(parsed.query) target = qs.get("target", [None])[0] if target: a_tag["href"] = unquote(target) - except Exception: - pass + except Exception as e: + logger.debug(f"Failed to unmask Zhihu link {href}: {e}")📝 Committable suggestion
🧰 Tools
🪛 Ruff (0.15.6)
[error] 62-63:
try-except-passdetected, consider logging the exception(S110)
[warning] 62-62: Do not catch blind exception:
Exception(BLE001)
🤖 Prompt for AI Agents