기본적인 프로그래밍 파이썬 : 송신 요구 scrapy를 사용하여 파이썬 포스트 구덩이

이 문서는 scrapy 보내기 POST 요청 구덩이의 사용을 설명 샤오 총통은 공유에 모두를 위해 지금은 매우 좋은 느낌뿐만 아니라 참조가 될 수 있습니다. 함께 작은 시리즈를 따라, 와서 보라
요청을 보내 포스트 요청을 사용하는
것이 얼마나 쉬운 사용 요청, 전송 요청이다보고 POST 요청을 보내도록

요청의 HTTP 모든 종류의 명백한 것을 간단한 API 수단을 요청합니다. 예를 들어, 당신은 그래서 HTTP POST 요청을 보낼 수 있습니다 :

>>>r = requests.post('http://httpbin.org/post', data = {'key':'value'})

매개 변수로 전달 될 수있는 사전 데이터를 사용하여, 또한 선조 통과 할

>>>payload = (('key1', 'value1'), ('key1', 'value2'))
>>>r = requests.post('http://httpbin.org/post', data=payload)
>>>print(r.text)
{
 ...
 "form": {
  "key1": [
   "value1",
   "value2"
  ]
 },
 ...
}

JSON은 전달

>>>import json
 
>>>url = 'https://api.github.com/some/endpoint'
>>>payload = {'some': 'data'}
 
>>>r = requests.post(url, data=json.dumps(payload))

버전 2.4.2의 새로운 기능을 추가 :

>>>url = 'https://api.github.com/some/endpoint'
>>>payload = {'some': 'data'}
 
>>>r = requests.post(url, json=payload)

즉, 당신은 단지 데이터 = 또는 JSON의 사용에 초점을 맞출 필요가 변경 매개 변수에 대한 작업을 수행 할 필요가 없습니다 =, 요청의 나머지는 도움이 당신에게 행해졌 다.

사용에 POST 요청을 보내 scrapy
우리가 다음에 예를 들어 볼 수있는 소스 코드를 요청하는 수행하는 요청 또는 로그인 매개 변수, 필요 게시물을 보낼 필요로 할 때 scrapy의 기본 요청하여 전송을 얻을

from scrapy.spider import CrawlSpider
from scrapy.selector import Selector
import scrapy
import json
class LaGou(CrawlSpider):
  name = 'myspider'
  def start_requests(self):
    yield scrapy.FormRequest(
      url='https://www.******.com/jobs/positionAjax.json?city=%E5%B9%BF%E5%B7%9E&needAddtionalResult=false',
      formdata={
        'first': 'true',#这里不能给bool类型的True,requests模块中可以
        'pn': '1',#这里不能给int类型的1,requests模块中可以
        'kd': 'python'
      },这里的formdata相当于requ模块中的data,key和value只能是键值对形式
      callback=self.parse
    )
  def parse(self, response):
    datas=json.loads(response.body.decode())['content']['positionResult']['result']
    for data in datas:
      print(data['companyFullName'] + str(data['positionId']))

공식 HTTP 송신 데이터의 POST를 통해에 FormRequest 사용 권장

return [FormRequest(url="http://www.example.com/post/action",
          formdata={'name': 'John Doe', 'age': '27'},
          callback=self.after_post)]

FormRequest 및 사용이 매개 변수를 전달 formdata 여기에 사용, 사전 여기를 참조하십시오.

그러나, 슈퍼 구덩이에 조금, 오늘 오후를 던져,이 방법의 사용 요청을 보내, 문제는 내가 원하는되지 않은 데이터를 반환 할 방법을
return scrapy.FormRequest(url, formdata=(payload))
오랜 시간 동안 인터넷을, 마지막 방법을 발견 scrapy.Request 전송 요청을 사용하여, 데이터 정상 취득 할 수있다.
return scrapy.Request(url, body=json.dumps(payload), method='POST', headers={'Content-Type': 'application/json'},)
참조 : Scrapymy에 보내기 POST 요청

_data = {'field1': 'value1', 'field2': 'value2'}
request = scrapy.Request( url, method='POST', 
             body=json.dumps(my_data), 
             headers={'Content-Type':'application/json'} )

FormRequest 및 요청 차이
문서는 거의 차이를 볼 수 있었다

The FormRequest class adds a new argument to the constructor. The remaining arguments are the same as for the Request class and are not documented here.
Parameters: formdata (dict or iterable of tuples) – is a dictionary (or iterable of (key, value) tuples) containing HTML Form data which will be url-encoded and assigned to the body of the request.

그는 FormRequest FormData 요청 본체 폼 데이터 또는 사전 튜플은 반복 될 수있는 포함하고, 변환을 받아, 새로운 파라미터를 첨가했다. 그리고 상속 요청의 FormRequest

class FormRequest(Request):
 
  def __init__(self, *args, **kwargs):
    formdata = kwargs.pop('formdata', None)
    if formdata and kwargs.get('method') is None:
      kwargs['method'] = 'POST'
 
    super(FormRequest, self).__init__(*args, **kwargs)
 
    if formdata:
      items = formdata.items() if isinstance(formdata, dict) else formdata
      querystr = _urlencode(items, self.encoding)
      if self.method == 'POST':
        self.headers.setdefault(b'Content-Type', b'application/x-www-form-urlencoded')
        self._set_body(querystr)
      else:
        self._set_url(self.url + ('&' if '?' in self.url else '?') + querystr)
      ###
 
 
def _urlencode(seq, enc):
  values = [(to_bytes(k, enc), to_bytes(v, enc))
       for k, vs in seq
       for v in (vs if is_listlike(vs) else [vs])]
  return urlencode(values, doseq=1)

'키 = 값 & K = V'기본 방법은 POST, 요청 봐입니다으로 변환됩니다 우리는 최종 { 'V': 'k는'가치 ''키를 '} 통과

class Request(object_ref):
 
  def __init__(self, url, callback=None, method='GET', headers=None, body=None,
         cookies=None, meta=None, encoding='utf-8', priority=0,
         dont_filter=False, errback=None, flags=None):
 
    self._encoding = encoding # this one has to be set first
    self.method = str(method).upper()

기본 방법은, 사실, 영향을받지 않습니다 GET이다. 당신은 여전히 ​​포스트 요청을 보낼 수 있습니다. 그것은 나를 요청에 정의 된 방법의 기본이되는 요청의 사용 요청을 생각합니다.

def request(method, url, **kwargs):
  """Constructs and sends a :class:`Request <Request>`.
 
  :param method: method for the new :class:`Request` object.
  :param url: URL for the new :class:`Request` object.
  :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
  :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.
  :param json: (optional) json data to send in the body of the :class:`Request`.
  :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.
  :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.
  :param files: (optional) Dictionary of ``'name': file-like-objects`` (or ``{'name': file-tuple}``) for multipart encoding upload.
    ``file-tuple`` can be a 2-tuple ``('filename', fileobj)``, 3-tuple ``('filename', fileobj, 'content_type')``
    or a 4-tuple ``('filename', fileobj, 'content_type', custom_headers)``, where ``'content-type'`` is a string
    defining the content type of the given file and ``custom_headers`` a dict-like object containing additional headers
    to add for the file.
  :param auth: (optional) Auth tuple to enable Basic/Digest/Custom HTTP Auth.
  :param timeout: (optional) How many seconds to wait for the server to send data
    before giving up, as a float, or a :ref:`(connect timeout, read
    timeout) <timeouts>` tuple.
  :type timeout: float or tuple
  :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.
  :type allow_redirects: bool
  :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.
  :param verify: (optional) Either a boolean, in which case it controls whether we verify
      the server's TLS certificate, or a string, in which case it must be a path
      to a CA bundle to use. Defaults to ``True``.
  :param stream: (optional) if ``False``, the response content will be immediately downloaded.
  :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.
  :return: :class:`Response <Response>` object
  :rtype: requests.Response
 
  Usage::
 
   >>> import requests
   >>> req = requests.request('GET', 'http://httpbin.org/get')
   <Response [200]>
  """
 
  # By using the 'with' statement we are sure the session is closed, thus we
  # avoid leaving sockets open which can trigger a ResourceWarning in some
  # cases, and look like a memory leak in others.
  with sessions.Session() as session:
    return session.request(method=method, url=url, **kwargs)

, 그리고 마지막으로 공공 기관 [프로그래머]의 수에서 좋은 평판을 추천하는 방법에 많은보다 더의 콘텐츠, 고참, 기술을 학습 경험, 면접 스킬, 직장 경험과 다른 공유 학습이 많이있다, 더 많은 우리가주의 깊게 준비한 제로 파이썬 프로그래머 기술의 타이밍을 설명하기 위해 매일 실제 프로젝트 데이터에 대한 소개 정보는주의 나 기억, 학습과 작은 세부 사항에주의 할 필요가하는 몇 가지 방법을 공유하는
그림 삽입 설명 여기

출시 여섯 개 원래 기사 · 원의 칭찬 0 · 조회수 5

추천

출처blog.csdn.net/chengxun02/article/details/104976025