(编辑:jimmy 日期: 2024/12/26 浏览:2)
scrapy有三种方法模拟登陆方式:
- 直接携带cookies
- 找url地址,发送post请求存储cookie
- 找到对应的form表单,自动解析input标签,自动解析post请求的url地址,自动带上数据,自动发送请求
import scrapy import re class Login1Spider(scrapy.Spider): name = 'login1' allowed_domains = ['github.com'] start_urls = ['https://github.com/NoobPythoner'] # 这是一个需要登陆以后才能访问的页面 def start_requests(self): # 重构start_requests方法 # 这个cookies_str是抓包获取的 cookies_str = '...' # 抓包获取 # 将cookies_str转换为cookies_dict cookies_dict = {i.split('=')[0]:i.split('=')[1] for i in cookies_str.split('; ')} yield scrapy.Request( self.start_urls[0], callback=self.parse, cookies=cookies_dict ) def parse(self, response): # 通过正则表达式匹配用户名来验证是否登陆成功 result_list = re.findall(r'noobpythoner|NoobPythoner', response.body.decode()) print(result_list) pass
注意:
scrapy中cookie不能够放在headers中,在构造请求的时候有专门的cookies参数,能够接受字典形式的coookie
在setting中设置ROBOTS协议、USER_AGENT
通过scrapy.FormRequest能够发送post请求,同时需要添加fromdata参数作为请求体,以及callback
yield scrapy.FormRequest( "https://github.com/session", formdata={ "authenticity_token":authenticity_token, "utf8":utf8, "commit":commit, "login":"****", "password":"****" }, callback=self.parse_login )
import scrapy import re class Login3Spider(scrapy.Spider): name = 'login3' allowed_domains = ['github.com'] start_urls = ['https://github.com/login'] def parse(self, response): yield scrapy.FormRequest.from_response( response, # 传入response对象,自动解析 # 可以通过xpath来定位form表单,当前页只有一个form表单时,将会自动定位 formxpath='//*[@id="login"]/form', formdata={'login': '****', 'password': '***'}, callback=self.parse_login ) def parse_login(self,response): ret = re.findall(r"noobpythoner|NoobPythoner", response.text) print(ret)