response.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on 2018-07-26 11:40:28
  4. ---------
  5. @summary:
  6. ---------
  7. @author: Boris
  8. @email: boris_liu@foxmail.com
  9. """
  10. import datetime
  11. import os
  12. import re
  13. import time
  14. from urllib.parse import urlparse, urlunparse, urljoin
  15. from bs4 import UnicodeDammit, BeautifulSoup
  16. from requests.cookies import RequestsCookieJar
  17. from requests.models import Response as res
  18. from w3lib.encoding import http_content_type_encoding, html_body_declared_encoding
  19. from feapder.network.selector import Selector
  20. from feapder.utils.log import log
  21. FAIL_ENCODING = "ISO-8859-1"
  22. # html 源码中的特殊字符,需要删掉,否则会影响etree的构建
  23. SPECIAL_CHARACTERS = [
  24. # 移除控制字符 全部字符列表 https://zh.wikipedia.org/wiki/%E6%8E%A7%E5%88%B6%E5%AD%97%E7%AC%A6
  25. "[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]"
  26. ]
  27. SPECIAL_CHARACTER_PATTERNS = [
  28. re.compile(special_character) for special_character in SPECIAL_CHARACTERS
  29. ]
  30. class Response(res):
  31. def __init__(self, response):
  32. super(Response, self).__init__()
  33. self.__dict__.update(response.__dict__)
  34. self._cached_selector = None
  35. self._cached_text = None
  36. self._cached_json = None
  37. self._encoding = None
  38. self.encoding_errors = "strict" # strict / replace / ignore
  39. @classmethod
  40. def from_dict(cls, response_dict):
  41. """
  42. 利用字典获取Response对象
  43. @param response_dict: 原生的response.__dict__
  44. @return:
  45. """
  46. cookie_jar = RequestsCookieJar()
  47. cookie_jar.update(other=response_dict["cookies"])
  48. response_dict["cookies"] = cookie_jar
  49. response_dict["elapsed"] = datetime.timedelta(
  50. 0, 0, response_dict["elapsed"]
  51. ) # 耗时
  52. response_dict["connection"] = None
  53. response_dict["_content_consumed"] = True
  54. response = res()
  55. response.__dict__.update(response_dict)
  56. return cls(response)
  57. @property
  58. def to_dict(self):
  59. response_dict = {
  60. "_content": self.content,
  61. "cookies": self.cookies.get_dict(),
  62. "encoding": self.encoding,
  63. "headers": self.headers,
  64. "status_code": self.status_code,
  65. "elapsed": self.elapsed.microseconds, # 耗时
  66. "url": self.url,
  67. }
  68. return response_dict
  69. def __clear_cache(self):
  70. self.__dict__["_cached_selector"] = None
  71. self.__dict__["_cached_text"] = None
  72. self.__dict__["_cached_json"] = None
  73. @property
  74. def encoding(self):
  75. """
  76. 编码优先级:自定义编码 > header中编码 > 页面编码 > 根据content猜测的编码
  77. """
  78. self._encoding = (
  79. self._encoding
  80. or self._headers_encoding()
  81. or self._body_declared_encoding()
  82. or self.apparent_encoding
  83. )
  84. return self._encoding
  85. @encoding.setter
  86. def encoding(self, val):
  87. self.__clear_cache()
  88. self._encoding = val
  89. code = encoding
  90. def _headers_encoding(self):
  91. """
  92. 从headers获取头部charset编码
  93. """
  94. content_type = self.headers.get("Content-Type") or self.headers.get(
  95. "content-type"
  96. )
  97. if content_type:
  98. return (
  99. http_content_type_encoding(content_type) or "utf-8"
  100. if "application/json" in content_type
  101. else None
  102. )
  103. def _body_declared_encoding(self):
  104. """
  105. 从html xml等获取<meta charset="编码">
  106. """
  107. return html_body_declared_encoding(self.content)
  108. def _get_unicode_html(self, html):
  109. if not html or not isinstance(html, bytes):
  110. return html
  111. converted = UnicodeDammit(html, is_html=True)
  112. if not converted.unicode_markup:
  113. raise Exception(
  114. "Failed to detect encoding of article HTML, tried: %s"
  115. % ", ".join(converted.tried_encodings)
  116. )
  117. html = converted.unicode_markup
  118. return html
  119. def _make_absolute(self, link):
  120. """Makes a given link absolute."""
  121. try:
  122. link = link.strip()
  123. # Parse the link with stdlib.
  124. parsed = urlparse(link)._asdict()
  125. # If link is relative, then join it with base_url.
  126. if not parsed["netloc"]:
  127. return urljoin(self.url, link)
  128. # Link is absolute; if it lacks a scheme, add one from base_url.
  129. if not parsed["scheme"]:
  130. parsed["scheme"] = urlparse(self.url).scheme
  131. # Reconstruct the URL to incorporate the new scheme.
  132. parsed = (v for v in parsed.values())
  133. return urlunparse(parsed)
  134. except Exception as e:
  135. log.error(
  136. "Invalid URL <{}> can't make absolute_link. exception: {}".format(
  137. link, e
  138. )
  139. )
  140. # Link is absolute and complete with scheme; nothing to be done here.
  141. return link
  142. def _absolute_links(self, text):
  143. regexs = [
  144. r'(<(?i)a.*?href\s*?=\s*?["\'])(.+?)(["\'])', # a
  145. r'(<(?i)img.*?src\s*?=\s*?["\'])(.+?)(["\'])', # img
  146. r'(<(?i)link.*?href\s*?=\s*?["\'])(.+?)(["\'])', # css
  147. r'(<(?i)script.*?src\s*?=\s*?["\'])(.+?)(["\'])', # js
  148. ]
  149. for regex in regexs:
  150. def replace_href(text):
  151. # html = text.group(0)
  152. link = text.group(2)
  153. absolute_link = self._make_absolute(link)
  154. # return re.sub(regex, r'\1{}\3'.format(absolute_link), html) # 使用正则替换,个别字符不支持。如该网址源代码http://permit.mep.gov.cn/permitExt/syssb/xxgk/xxgk!showImage.action?dataid=0b092f8115ff45c5a50947cdea537726
  155. return text.group(1) + absolute_link + text.group(3)
  156. text = re.sub(regex, replace_href, text, flags=re.S)
  157. return text
  158. def _del_special_character(self, text):
  159. """
  160. 删除特殊字符
  161. """
  162. for special_character_pattern in SPECIAL_CHARACTER_PATTERNS:
  163. text = special_character_pattern.sub("", text)
  164. return text
  165. @property
  166. def __text(self):
  167. """Content of the response, in unicode.
  168. If Response.encoding is None, encoding will be guessed using
  169. ``chardet``.
  170. The encoding of the response content is determined based solely on HTTP
  171. headers, following RFC 2616 to the letter. If you can take advantage of
  172. non-HTTP knowledge to make a better guess at the encoding, you should
  173. set ``r.encoding`` appropriately before accessing this property.
  174. """
  175. if not self.content:
  176. return ""
  177. # Decode unicode from given encoding.
  178. try:
  179. content = str(self.content, self.encoding, errors=self.encoding_errors)
  180. except (LookupError, TypeError):
  181. # A LookupError is raised if the encoding was not found which could
  182. # indicate a misspelling or similar mistake.
  183. #
  184. # A TypeError can be raised if encoding is None
  185. #
  186. # So we try blindly encoding.
  187. content = str(self.content, errors=self.encoding_errors)
  188. return content
  189. @property
  190. def text(self):
  191. if self._cached_text is None:
  192. if self.encoding and self.encoding.upper() != FAIL_ENCODING:
  193. try:
  194. self._cached_text = self.__text
  195. except UnicodeDecodeError:
  196. self._cached_text = self._get_unicode_html(self.content)
  197. else:
  198. self._cached_text = self._get_unicode_html(self.content)
  199. if self._cached_text:
  200. self._cached_text = self._absolute_links(self._cached_text)
  201. self._cached_text = self._del_special_character(self._cached_text)
  202. return self._cached_text
  203. @text.setter
  204. def text(self, html):
  205. self._cached_text = html
  206. self._cached_text = self._absolute_links(self._cached_text)
  207. self._cached_text = self._del_special_character(self._cached_text)
  208. self._cached_selector = Selector(self.text)
  209. @property
  210. def json(self, **kwargs):
  211. if self._cached_json is None:
  212. self.encoding = self.encoding or "utf-8"
  213. self._cached_json = super(Response, self).json(**kwargs)
  214. return self._cached_json
  215. @property
  216. def content(self):
  217. content = super(Response, self).content
  218. return content
  219. @property
  220. def is_html(self):
  221. content_type = self.headers.get("Content-Type", "")
  222. if "text/html" in content_type:
  223. return True
  224. else:
  225. return False
  226. @property
  227. def selector(self):
  228. if self._cached_selector is None:
  229. self._cached_selector = Selector(self.text)
  230. return self._cached_selector
  231. def bs4(self, features="html.parser"):
  232. soup = BeautifulSoup(self.text, features)
  233. return soup
  234. def extract(self):
  235. return self.selector.get()
  236. def xpath(self, query, **kwargs):
  237. return self.selector.xpath(query, **kwargs)
  238. def css(self, query):
  239. return self.selector.css(query)
  240. def re(self, regex, replace_entities=False):
  241. """
  242. @summary: 正则匹配
  243. 注意:网页源码<a class='page-numbers'... 会被处理成<a class="page-numbers" ; 写正则时要写<a class="(.*?)"。 但不会改非html的文本引号格式
  244. 为了使用方便,正则单双引号自动处理为不敏感
  245. ---------
  246. @param regex: 正则或者re.compile
  247. @param replace_entities: 为True时 去掉&nbsp;等字符, 转义&quot;为 " 等, 会使网页结构发生变化。如在网页源码中提取json, 建议设置成False
  248. ---------
  249. @result: 列表
  250. """
  251. # 将单双引号设置为不敏感
  252. if isinstance(regex, str):
  253. regex = re.sub("['\"]", "['\"]", regex)
  254. return self.selector.re(regex, replace_entities)
  255. def re_first(self, regex, default=None, replace_entities=False):
  256. """
  257. @summary: 正则匹配
  258. 注意:网页源码<a class='page-numbers'... 会被处理成<a class="page-numbers" ; 写正则时要写<a class="(.*?)"。 但不会改非html的文本引号格式
  259. 为了使用方便,正则单双引号自动处理为不敏感
  260. ---------
  261. @param regex: 正则或者re.compile
  262. @param default: 未匹配到, 默认值
  263. @param replace_entities: 为True时 去掉&nbsp;等字符, 转义&quot;为 " 等, 会使网页结构发生变化。如在网页源码中提取json, 建议设置成False
  264. ---------
  265. @result: 第一个值或默认值
  266. """
  267. # 将单双引号设置为不敏感
  268. if isinstance(regex, str):
  269. regex = re.sub("['\"]", "['\"]", regex)
  270. return self.selector.re_first(regex, default, replace_entities)
  271. def close_browser(self, request):
  272. if hasattr(self, "browser"):
  273. request._webdriver_pool.remove(self.browser)
  274. del self.browser
  275. def __del__(self):
  276. self.close()
  277. def open(self, delete_temp_file=False):
  278. with open("temp.html", "w", encoding=self.encoding, errors="replace") as html:
  279. self.encoding_errors = "replace"
  280. html.write(self.text)
  281. os.system("open temp.html")
  282. if delete_temp_file:
  283. time.sleep(1)
  284. os.remove("temp.html")