您好,登錄后才能下訂單哦!
怎么利用Scrapy框架登錄網站?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
一、使用cookies登錄網站
import scrapy class LoginSpider(scrapy.Spider): name = 'login' allowed_domains = ['xxx.com'] start_urls = ['https://www.xxx.com/xx/'] cookies = "" def start_requests(self): for url in self.start_urls: yield scrapy.Request(url, cookies=self.cookies, callback=self.parse) def parse(self, response): with open("01login.html", "wb") as f: f.write(response.body)
二、發送post請求登錄, 要手動解析網頁獲取登錄參數
import scrapy class LoginSpider(scrapy.Spider): name='login_code' allowed_domains = ['xxx.com'] #1. 登錄頁面 start_urls = ['https://www.xxx.com/login/'] def parse(self, response): #2. 代碼登錄 login_url='https://www.xxx.com/login' formdata={ "username":"xxx", "pwd":"xxx", "formhash":response.xpath("//input[@id='formhash']/@value").extract_first(), "backurl":response.xpath("//input[@id='backurl']/@value").extract_first() } #3. 發送登錄請求post yield scrapy.FormRequest(login_url, formdata=formdata, callback=self.parse_login) def parse_login(self, response): #4.訪問目標頁面 member_url="https://www.xxx.com/member" yield scrapy.Request(member_url, callback=self.parse_member) def parse_member(self, response): with open("02login.html",'wb') as f: f.write(response.body)
三、發送post請求登錄, 自動解析網頁獲取登錄參數
import scrapy class LoginSpider(scrapy.Spider): name='login_code2' allowed_domains = ['xxx.com'] #1. 登錄頁面 start_urls = ['https://www.xxx.com/login/'] def parse(self, response): #2. 代碼登錄 login_url='https://www.xxx.com/login' formdata={ "username":"xxx", "pwd":"xxx" } #3. 發送登錄請求post yield scrapy.FormRequest.from_response( response, formxpath="//*[@id='login_pc']", formdata=formdata, method="POST", #覆蓋之前的get請求 callback=self.parse_login ) def parse_login(self, response): #4.訪問目標頁面 member_url="https://www.xxx.com/member" yield scrapy.Request(member_url, callback=self.parse_member) def parse_member(self, response): with open("03login.html",'wb') as f: f.write(response.body)
看完上述內容,你們掌握怎么利用Scrapy框架登錄網站的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。