目录
  1. 1. 在scrapy框架下实现模拟登录
    1. 1.1. Response对象:
    2. 1.2. Request对象:
    3. 1.3. 注意:
    4. 1.4. 示例:
在scrapy框架下实现模拟登录(1)

在scrapy框架下实现模拟登录

Response对象:

response对象有以下的属性,可以用来提取数据:

  1. meta:从其他请求传过来的meta属性,可以用来保持多个请求之间的数据链接。
  2. encoding: 返回当前字符串编码和解码的格式。
  3. text: 将返回来的数据作为unicode字符串返回。
  4. body: 将返回来的数据作为bytes字符串返回。
  5. xpath: xpath选择器。
  6. css: css选择器。

Request对象:

  1. url: request对象发送请求的链接。
  2. callback: 回调函数,即下载器下载完成后执行的回调函数。
  3. method: 请求方法,默认是get,如果是POST一般不用这个方法,使用FormRequest对象。
  4. headers: 请求头,对于一些固定的设置,放在setting.py中指定即可,对于非固定的,可以在发送请求时设置。
  5. meta:可用于不同请求之间传送数据。
  6. encoding: 编码,默认utf-8。
  7. dont_filter: 表示不由调度器过滤,在执行多次请求的时候用的比较多。
  8. errback: 一般在出现错误的时候执行的函数。

注意:

​ 在请求数据发送POST请求时,需要调用Request子类FormRequest来实现。需要删除默认的parse方法,重新定义一个start_requests()方法。源代码中的start_requests()原方法采用的是get请求。

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#在spider模块的renren.py里面
import scrapy
import time

class RenrenSpider(scrapy.Spider):
name = "renren"
#allowed_domains = ["'renren.com'"]
start_urls = ['http://www.renren.com/']
url='http://www.renren.com/'

def start_requests(self):
base_url='http://www.renren.com/ajaxLogin/login?1=1&uniqueTimestamp='
s=time.strftime("%S")
ms=int(round(time.time()%(int(time.time())),3)*1000)
date_time='20188010'+str(s)+str(ms)
login_url=base_url+date_time
data={'email':'(账号)',
'icode':'',
'origURL':'http://www.renren.com/home',
'domain':'renren.com',
'key_id':'1',####注意这里面一定是字符型1,整型1会报错。如果使用
###request.session()应该没有这个问题
'captcha_type':'web_login',
'password':'(复制即可)',
'rkey':'fee3c0249fcf32f072eb0a4ccd82fa98',
'f':'https%3A%2F%2Fwww.baidu.com%2Flink%3Furl%3DLwaiZlZgTeev7o9XOVRn3fvV4cWe7mW2wCUyYq73YZK%26wd%3D%26eqid%3D986b249200000e32000000035b8b47ec',
}
request = scrapy.FormRequest(url=login_url,formdata=data,callback=self.parse_login,dont_filter=True)
yield request
#在这一步中运用FormRequest类发送POST请求到login_url,回调给parse_login进行解析,yield一个request对象可供爬虫方法正常调用
def parse_login(self,response):
yield scrapy.Request(url='http://www.renren.com/880151247/profile',callback=self.parse_text,dont_filter=True)
#为了验证是否登录成功,打开个人文档
def parse_text(self,response):
with open(r'E:\renrenwang\renrenwang\大鹏.html','w',encoding='utf-8') as f:
f.write(response.text)
文章作者: jiangzuojiben
文章链接: http://jiangzuojiben.github.io/2019/10/22/%E5%9C%A8scrapy%E6%A1%86%E6%9E%B6%E4%B8%8B%E5%AE%9E%E7%8E%B0%E6%A8%A1%E6%8B%9F%E7%99%BB%E5%BD%95-1/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 jiangzuojiben