spiderApp.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. import os
  2. from typing import Literal, Optional, TypedDict
  3. import requests
  4. class RequestParamsDict(TypedDict, total=False):
  5. url: Optional[str]
  6. request: Optional[Literal["http", "chrome", "smart"]]
  7. limit: Optional[int]
  8. return_format: Optional[Literal["raw", "markdown", "html2text", "text", "bytes"]]
  9. tld: Optional[bool]
  10. depth: Optional[int]
  11. cache: Optional[bool]
  12. budget: Optional[dict[str, int]]
  13. locale: Optional[str]
  14. cookies: Optional[str]
  15. stealth: Optional[bool]
  16. headers: Optional[dict[str, str]]
  17. anti_bot: Optional[bool]
  18. metadata: Optional[bool]
  19. viewport: Optional[dict[str, int]]
  20. encoding: Optional[str]
  21. subdomains: Optional[bool]
  22. user_agent: Optional[str]
  23. store_data: Optional[bool]
  24. gpt_config: Optional[list[str]]
  25. fingerprint: Optional[bool]
  26. storageless: Optional[bool]
  27. readability: Optional[bool]
  28. proxy_enabled: Optional[bool]
  29. respect_robots: Optional[bool]
  30. query_selector: Optional[str]
  31. full_resources: Optional[bool]
  32. request_timeout: Optional[int]
  33. run_in_background: Optional[bool]
  34. skip_config_checks: Optional[bool]
  35. class Spider:
  36. def __init__(self, api_key: Optional[str] = None):
  37. """
  38. Initialize the Spider with an API key.
  39. :param api_key: A string of the API key for Spider. Defaults to the SPIDER_API_KEY environment variable.
  40. :raises ValueError: If no API key is provided.
  41. """
  42. self.api_key = api_key or os.getenv("SPIDER_API_KEY")
  43. if self.api_key is None:
  44. raise ValueError("No API key provided")
  45. def api_post(
  46. self,
  47. endpoint: str,
  48. data: dict,
  49. stream: bool,
  50. content_type: str = "application/json",
  51. ):
  52. """
  53. Send a POST request to the specified API endpoint.
  54. :param endpoint: The API endpoint to which the POST request is sent.
  55. :param data: The data (dictionary) to be sent in the POST request.
  56. :param stream: Boolean indicating if the response should be streamed.
  57. :return: The JSON response or the raw response stream if stream is True.
  58. """
  59. headers = self._prepare_headers(content_type)
  60. response = self._post_request(f"https://api.spider.cloud/v1/{endpoint}", data, headers, stream)
  61. if stream:
  62. return response
  63. elif response.status_code == 200:
  64. return response.json()
  65. else:
  66. self._handle_error(response, f"post to {endpoint}")
  67. def api_get(self, endpoint: str, stream: bool, content_type: str = "application/json"):
  68. """
  69. Send a GET request to the specified endpoint.
  70. :param endpoint: The API endpoint from which to retrieve data.
  71. :return: The JSON decoded response.
  72. """
  73. headers = self._prepare_headers(content_type)
  74. response = self._get_request(f"https://api.spider.cloud/v1/{endpoint}", headers, stream)
  75. if response.status_code == 200:
  76. return response.json()
  77. else:
  78. self._handle_error(response, f"get from {endpoint}")
  79. def get_credits(self):
  80. """
  81. Retrieve the account's remaining credits.
  82. :return: JSON response containing the number of credits left.
  83. """
  84. return self.api_get("credits", stream=False)
  85. def scrape_url(
  86. self,
  87. url: str,
  88. params: Optional[RequestParamsDict] = None,
  89. stream: bool = False,
  90. content_type: str = "application/json",
  91. ):
  92. """
  93. Scrape data from the specified URL.
  94. :param url: The URL from which to scrape data.
  95. :param params: Optional dictionary of additional parameters for the scrape request.
  96. :return: JSON response containing the scraping results.
  97. """
  98. params = params or {}
  99. # Add { "return_format": "markdown" } to the params if not already present
  100. if "return_format" not in params:
  101. params["return_format"] = "markdown"
  102. # Set limit to 1
  103. params["limit"] = 1
  104. return self.api_post("crawl", {"url": url, **(params or {})}, stream, content_type)
  105. def crawl_url(
  106. self,
  107. url: str,
  108. params: Optional[RequestParamsDict] = None,
  109. stream: bool = False,
  110. content_type: str = "application/json",
  111. ):
  112. """
  113. Start crawling at the specified URL.
  114. :param url: The URL to begin crawling.
  115. :param params: Optional dictionary with additional parameters to customize the crawl.
  116. :param stream: Boolean indicating if the response should be streamed. Defaults to False.
  117. :return: JSON response or the raw response stream if streaming enabled.
  118. """
  119. params = params or {}
  120. # Add { "return_format": "markdown" } to the params if not already present
  121. if "return_format" not in params:
  122. params["return_format"] = "markdown"
  123. return self.api_post("crawl", {"url": url, **(params or {})}, stream, content_type)
  124. def links(
  125. self,
  126. url: str,
  127. params: Optional[RequestParamsDict] = None,
  128. stream: bool = False,
  129. content_type: str = "application/json",
  130. ):
  131. """
  132. Retrieve links from the specified URL.
  133. :param url: The URL from which to extract links.
  134. :param params: Optional parameters for the link retrieval request.
  135. :return: JSON response containing the links.
  136. """
  137. return self.api_post("links", {"url": url, **(params or {})}, stream, content_type)
  138. def extract_contacts(
  139. self,
  140. url: str,
  141. params: Optional[RequestParamsDict] = None,
  142. stream: bool = False,
  143. content_type: str = "application/json",
  144. ):
  145. """
  146. Extract contact information from the specified URL.
  147. :param url: The URL from which to extract contact information.
  148. :param params: Optional parameters for the contact extraction.
  149. :return: JSON response containing extracted contact details.
  150. """
  151. return self.api_post(
  152. "pipeline/extract-contacts",
  153. {"url": url, **(params or {})},
  154. stream,
  155. content_type,
  156. )
  157. def label(
  158. self,
  159. url: str,
  160. params: Optional[RequestParamsDict] = None,
  161. stream: bool = False,
  162. content_type: str = "application/json",
  163. ):
  164. """
  165. Apply labeling to data extracted from the specified URL.
  166. :param url: The URL to label data from.
  167. :param params: Optional parameters to guide the labeling process.
  168. :return: JSON response with labeled data.
  169. """
  170. return self.api_post("pipeline/label", {"url": url, **(params or {})}, stream, content_type)
  171. def _prepare_headers(self, content_type: str = "application/json"):
  172. return {
  173. "Content-Type": content_type,
  174. "Authorization": f"Bearer {self.api_key}",
  175. "User-Agent": "Spider-Client/0.0.27",
  176. }
  177. def _post_request(self, url: str, data, headers, stream=False):
  178. return requests.post(url, headers=headers, json=data, stream=stream)
  179. def _get_request(self, url: str, headers, stream=False):
  180. return requests.get(url, headers=headers, stream=stream)
  181. def _delete_request(self, url: str, headers, stream=False):
  182. return requests.delete(url, headers=headers, stream=stream)
  183. def _handle_error(self, response, action):
  184. if response.status_code in {402, 409, 500}:
  185. error_message = response.json().get("error", "Unknown error occurred")
  186. raise Exception(f"Failed to {action}. Status code: {response.status_code}. Error: {error_message}")
  187. else:
  188. raise Exception(f"Unexpected error occurred while trying to {action}. Status code: {response.status_code}")