scrapy 发送post请求

登录人人网为例

1.想要发送post请求,那么使用'scrapy.FormRequest'方法,可以方便的指定表单数据

2.如果想在爬虫一开始的时候就发送post请求,那么应该重写'start_requests'方法,在这个方法中发送post请求

spider.py

 1 import scrapy
 2 
 3 
 4 class RenrenSpider(scrapy.Spider):
 5     name = 'renren'
 6     allowed_domains = ['renren.com']
 7     start_urls = ['http://renren.com/']
 8 
 9     def start_requests(self):
10         url = 'http://www.renren.com/PLogin.do'
11         data = {'email': 'user name', 'password': 'user password'}
12         request = scrapy.FormRequest(url, formdata=data, callback=self.parse_page)    #发送post请求
13         yield request
14 
15     def parse_page(self, response):
16         request = scrapy.Request(url='http://www.renren.com/880151247/profile', callback=self.parse_profile)    #访问大鹏个人主页
17         yield request
18 
19     def parse_profile(self, response):
20         with open('dapeng.html', 'w', encoding='utf-8') as fp:
21             fp.write(response.text)    #如果返回个人主页代码则说明登录成功#

返回结果

dapeng.html 部分代码

 1 <!Doctype html>
 2 <html class="nx-main860">
 3 <head>
 4     <meta name="Description" content="人人网 校内是一个真实的社交网络,联络你和你周围的朋友。 加入人人网校内你可以:联络朋友,了解他们的最新动态;和朋友分享相片、音乐和电影;找到老同学,结识新朋友;用照片和日志记录生活,展示自我。"/>
 5     <meta name="Keywords" content="Xiaonei,Renren,校内,大学,同学,同事,白领,个人主页,博客,相册,群组,社区,交友,聊天,音乐,视频,校园,人人,人人网"/>
 6     <title>人人网 - 大鹏董成鹏</title>
 7     <meta charset="utf-8"/>
 8 <link rel="shortcut icon" type="image/x-icon" href="http://a.xnimg.cn/favicon-rr.ico?ver=3" />
 9 <link rel="apple-touch-icon" href="http://a.xnimg.cn/wap/apple_icon_.png" />
10 <link rel="stylesheet" type="text/css" href="http://s.xnimg.cn/a86614/nx/core/base.css">
11 <script type="text/javascript">
12 if(typeof nx === 'undefined'){
13 var nx = {};
14 }

说明登录成功

别忘了设置settings.py中的请求头和爬虫协议

原文地址:https://www.cnblogs.com/MC-Curry/p/9516675.html