-
Notifications
You must be signed in to change notification settings - Fork 378
feat: add respect_robots_txt_file
option
#1162
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
Show all changes
21 commits
Select commit
Hold shift + click to select a range
427b00a
basic_robots_allow
Mantisus 638b5be
add respect robots_txt_file
Mantisus 33be1c8
update load
Mantisus a44dff1
change `RobotFileParser` to `Protego`
Mantisus 538672e
add tests
Mantisus b9b35be
fix
Mantisus a49ab66
update tests
Mantisus 46a2356
update TODO comments
Mantisus 10077b6
update docstrings
Mantisus b3e9789
Apply suggestions from code review
Mantisus 4f4529e
Update src/crawlee/crawlers/_basic/_basic_crawler.py
Mantisus 8973618
fix docstrings
Mantisus 73a7bc6
change staticmethod to classmethod
Mantisus 8039fb5
Update src/crawlee/_utils/robots.py
Mantisus 125804c
add _robots_txt_locks_cache
Mantisus 4b7346b
update `pyproject.toml`
Mantisus e6099ed
update docstrings
Mantisus 41b803d
add docs example
Mantisus 8f25d83
update comment
Mantisus d46a3c6
resolve
Mantisus 260ad92
one lock to rule them all
Mantisus 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import asyncio | ||
|
||
from crawlee.crawlers import ( | ||
BeautifulSoupCrawler, | ||
BeautifulSoupCrawlingContext, | ||
) | ||
|
||
|
||
async def main() -> None: | ||
# Initialize the crawler with robots.txt compliance enabled | ||
crawler = BeautifulSoupCrawler(respect_robots_txt_file=True) | ||
|
||
@crawler.router.default_handler | ||
async def request_handler(context: BeautifulSoupCrawlingContext) -> None: | ||
context.log.info(f'Processing {context.request.url} ...') | ||
|
||
# Start the crawler with the specified URLs | ||
# The crawler will check the robots.txt file before making requests | ||
# In this example, 'https://news.ycombinator.com/login' will be skipped | ||
# because it's disallowed in the site's robots.txt file | ||
await crawler.run( | ||
['https://news.ycombinator.com/', 'https://news.ycombinator.com/login'] | ||
) | ||
|
||
|
||
if __name__ == '__main__': | ||
asyncio.run(main()) |
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,21 @@ | ||
--- | ||
id: respect-robots-txt-file | ||
title: Respect robots.txt file | ||
--- | ||
|
||
import ApiLink from '@site/src/components/ApiLink'; | ||
import RunnableCodeBlock from '@site/src/components/RunnableCodeBlock'; | ||
|
||
import RespectRobotsTxt from '!!raw-loader!roa-loader!./code_examples/respect_robots_txt_file.py'; | ||
|
||
This example demonstrates how to configure your crawler to respect the rules established by websites for crawlers as described in the [robots.txt](https://www.robotstxt.org/robotstxt.html) file. | ||
|
||
To configure `Crawlee` to follow the `robots.txt` file, set the parameter `respect_robots_txt_file=True` in <ApiLink to="class/BasicCrawlerOptions">`BasicCrawlerOptions`</ApiLink>. In this case, `Crawlee` will skip any URLs forbidden in the website's robots.txt file. | ||
|
||
As an example, let's look at the website `https://news.ycombinator.com/` and its corresponding [robots.txt](https://news.ycombinator.com/robots.txt) file. Since the file has a rule `Disallow: /login`, the URL `https://news.ycombinator.com/login` will be automatically skipped. | ||
|
||
The code below demonstrates this behavior using the <ApiLink to="class/BeautifulSoupCrawler">`BeautifulSoupCrawler`</ApiLink>: | ||
|
||
<RunnableCodeBlock className="language-python" language="python"> | ||
{RespectRobotsTxt} | ||
</RunnableCodeBlock> |
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,85 @@ | ||
from __future__ import annotations | ||
|
||
from typing import TYPE_CHECKING | ||
|
||
from protego import Protego | ||
from yarl import URL | ||
|
||
from crawlee._utils.web import is_status_code_client_error | ||
|
||
if TYPE_CHECKING: | ||
from typing_extensions import Self | ||
|
||
from crawlee.http_clients import HttpClient | ||
from crawlee.proxy_configuration import ProxyInfo | ||
|
||
|
||
class RobotsTxtFile: | ||
def __init__(self, url: str, robots: Protego) -> None: | ||
self._robots = robots | ||
self._original_url = URL(url).origin() | ||
|
||
@classmethod | ||
async def from_content(cls, url: str, content: str) -> Self: | ||
"""Create a `RobotsTxtFile` instance from the given content. | ||
|
||
Args: | ||
url: The URL associated with the robots.txt file. | ||
content: The raw string content of the robots.txt file to be parsed. | ||
""" | ||
robots = Protego.parse(content) | ||
return cls(url, robots) | ||
|
||
@classmethod | ||
async def find(cls, url: str, http_client: HttpClient, proxy_info: ProxyInfo | None = None) -> Self: | ||
"""Determine the location of a robots.txt file for a URL and fetch it. | ||
|
||
Args: | ||
url: The URL whose domain will be used to find the corresponding robots.txt file. | ||
http_client: Optional `ProxyInfo` to be used when fetching the robots.txt file. If None, no proxy is used. | ||
proxy_info: The `HttpClient` instance used to perform the network request for fetching the robots.txt file. | ||
""" | ||
robots_url = URL(url).with_path('/robots.txt') | ||
return await cls.load(str(robots_url), http_client, proxy_info) | ||
|
||
@classmethod | ||
async def load(cls, url: str, http_client: HttpClient, proxy_info: ProxyInfo | None = None) -> Self: | ||
"""Load the robots.txt file for a given URL. | ||
|
||
Args: | ||
url: The direct URL of the robots.txt file to be loaded. | ||
http_client: The `HttpClient` instance used to perform the network request for fetching the robots.txt file. | ||
proxy_info: Optional `ProxyInfo` to be used when fetching the robots.txt file. If None, no proxy is used. | ||
""" | ||
response = await http_client.send_request(url, proxy_info=proxy_info) | ||
body = b'User-agent: *\nAllow: /' if is_status_code_client_error(response.status_code) else response.read() | ||
|
||
robots = Protego.parse(body.decode('utf-8')) | ||
|
||
return cls(url, robots) | ||
|
||
def is_allowed(self, url: str, user_agent: str = '*') -> bool: | ||
"""Check if the given URL is allowed for the given user agent. | ||
|
||
Args: | ||
url: The URL to check against the robots.txt rules. | ||
user_agent: The user-agent string to check permissions for. Defaults to '*' which matches any user-agent. | ||
""" | ||
check_url = URL(url) | ||
if check_url.origin() != self._original_url: | ||
return True | ||
return bool(self._robots.can_fetch(str(check_url), user_agent)) | ||
|
||
def get_sitemaps(self) -> list[str]: | ||
"""Get the list of sitemaps urls from the robots.txt file.""" | ||
return list(self._robots.sitemaps) | ||
|
||
def get_crawl_delay(self, user_agent: str = '*') -> int | None: | ||
"""Get the crawl delay for the given user agent. | ||
|
||
Args: | ||
user_agent: The user-agent string to check the crawl delay for. Defaults to '*' which matches any | ||
user-agent. | ||
""" | ||
crawl_delay = self._robots.crawl_delay(user_agent) | ||
return int(crawl_delay) if crawl_delay is not None else None |
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
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
Oops, something went wrong.
Oops, something went wrong.
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.
It's fun to see another scrapy project here, but I guess that it guarantees some stability, so... all good.
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.
Yes, I was planning to use
RobotFileParser
, but it doesn't support Google's specification. 😞