-
Notifications
You must be signed in to change notification settings - Fork 227
Feat: Add Sogou Text Backend #392
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
Open
scarletkc
wants to merge
7
commits into
deedy5:main
Choose a base branch
from
scarletkc:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
6d39cae
feat(sogou): add text backend
scarletkc ad02ff6
Refactor imports in sogou.py for type checking
scarletkc d3daacd
Update .gitignore and improve README structure
scarletkc 3b49972
Revert "Update .gitignore and improve README structure"
scarletkc d082e65
Simplify Sogou result post-processing logic
scarletkc e1a826e
Improve Sogou engine to resolve wrapper links using data-url
scarletkc f0aa30f
Merge branch 'main' into main
scarletkc 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
Some comments aren't visible on the classic Files Changed page.
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -137,7 +137,7 @@ celerybeat.pid | |
| # Environments | ||
| .env | ||
| .envrc | ||
| .venv | ||
| .venv* | ||
| env/ | ||
| venv/ | ||
| ENV/ | ||
|
|
||
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 |
|---|---|---|
|
|
@@ -190,6 +190,7 @@ def version() -> str: | |
| "duckduckgo", | ||
| "google", | ||
| "mojeek", | ||
| "sogou", | ||
| "yandex", | ||
| "yahoo", | ||
| "wikipedia", | ||
|
|
||
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,89 @@ | ||
| """Sogou search engine implementation.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| import re | ||
| from typing import TYPE_CHECKING, Any, ClassVar | ||
| from urllib.parse import urljoin | ||
|
|
||
| if TYPE_CHECKING: | ||
| from collections.abc import Mapping | ||
|
|
||
| from ddgs.base import BaseSearchEngine | ||
| from ddgs.results import TextResult | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class Sogou(BaseSearchEngine[TextResult]): | ||
| """Sogou search engine.""" | ||
|
|
||
| name = "sogou" | ||
| category = "text" | ||
| provider = "sogou" | ||
|
|
||
| search_url = "https://www.sogou.com/web" | ||
| search_method = "GET" | ||
|
|
||
| items_xpath = "//div[contains(@class, 'vrwrap') and not(contains(@class, 'hint'))]" | ||
| elements_xpath: ClassVar[Mapping[str, str]] = { | ||
| "title": ".//h3//a//text()", | ||
| "href": ".//h3//a/@href", | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "href": use xpath from _data_url_xpath |
||
| "body": ".//div[contains(@class, 'space-txt')]//text()", | ||
| } | ||
|
|
||
| _redirect_pattern = re.compile(r"window\.location\.replace\([\"'](?P<url>[^\"']+)[\"']\)") | ||
| _meta_refresh_pattern = re.compile(r"URL='?(?P<url>[^'\"]+)", re.IGNORECASE) | ||
|
|
||
| def __init__(self, proxy: str | None = None, timeout: int | None = None, *, verify: bool | str = True) -> None: | ||
| super().__init__(proxy=proxy, timeout=timeout, verify=verify) | ||
| self._href_cache: dict[str, str] = {} | ||
|
|
||
| def build_payload( | ||
| self, | ||
| query: str, | ||
| region: str, # noqa: ARG002 | ||
| safesearch: str, # noqa: ARG002 | ||
| timelimit: str | None, | ||
| page: int = 1, | ||
| **kwargs: str, # noqa: ARG002 | ||
| ) -> dict[str, Any]: | ||
| """Build a payload for the search request.""" | ||
| payload = {"query": query, "ie": "utf8", "p": "40040100", "dp": "1"} | ||
| if timelimit: | ||
| payload["tsn"] = {"d": "1", "w": "7", "m": "30", "y": "365"}[timelimit] | ||
| if page > 1: | ||
| payload["page"] = str(page) | ||
| return payload | ||
|
|
||
| def post_extract_results(self, results: list[TextResult]) -> list[TextResult]: | ||
|
Owner
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. validate href in post_extract_results |
||
| """Post-process search results.""" | ||
| post_results = [] | ||
| for result in results: | ||
| if result.href and result.title: | ||
| result.href = self._normalize_href(result.href) | ||
| post_results.append(result) | ||
| return post_results | ||
|
|
||
| def _normalize_href(self, href: str) -> str: | ||
| """Normalize Sogou link to an absolute URL and resolve redirects when possible.""" | ||
| href = urljoin(self.search_url, href) | ||
| if "sogou.com/link?url=" not in href: | ||
| return href | ||
|
|
||
| if href in self._href_cache: | ||
| return self._href_cache[href] | ||
|
|
||
| resolved = href | ||
| try: | ||
| resp = self.http_client.request("GET", href) | ||
scarletkc marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| except Exception as exc: # noqa: BLE001 | ||
| logger.debug("Error resolving Sogou link %s: %r", href, exc) | ||
| else: | ||
| if resp.status_code == 200 and resp.text: | ||
| match = self._redirect_pattern.search(resp.text) or self._meta_refresh_pattern.search(resp.text) | ||
| if match: | ||
| resolved = match.group("url") | ||
| self._href_cache[href] = resolved | ||
| return resolved | ||
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.
Uh oh!
There was an error while loading. Please reload this page.
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.
please delete
from __future__ import annotations