注:由于没有找到不需验证码登录的网站,所以本文代码均未经过验证,仅作了解原理之用
1.使用 cmd 命令行创建项目
scrapy startproject almost
scrapy genspider -t basic login baidu.com
2.抓包分析登录网页,使用flider,提取登录格式
得到登录url:https://passport.baidu.com/v2/api/?login
与提交表单格式:username=17667529698&password=
3.scrapy编写
# -*- coding: utf-8 -*-
import scrapy
#j加载scrapy.http
from scrapy.http import Request,FormRequest
class LoginSpider(scrapy.Spider):
name = 'login'
allowed_domains = ['baidu.com']
start_urls = ['http://baidu.com/']
#添加报头
header={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0"}
#重置start网址(可将起始的 start_urls注释掉)
def start_requests()
return[Request("https://passport.baidu.com/v2/api/?login")]
def parse(self, response):
#设置要传递的post信息
data={
"username":"",
"password":""
}
# 通过FormRequest.form_response()进行模拟登录
return [FormRequest.form_response(response,
#设置cookie信息
mata={"cookiejar":response.meta["cookiejar"]},#键值
#设置headerm模拟浏览器
headers=self.header,
#设置post表单信息
formdata=data,
#设置回调函数,此时回调函数为next()(自己定义)
callback=self.next(),
)]
def next(self,response):
print(response.xpath("/html/head/title/text()").extract())
yield Request("")#这里填写登录成功后需跳转页面的网址
def next2(self,response):
print(response.xpath("/html/head/title/text()").extract())#输出跳转后的页面
需注意的问题:
1.有的网页访问时会有robot协议的影响,注意取消
2.百度登录密码经过加密,没能使用,还需努力!