溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎樣使用selenium和requests組合實現(xiàn)登錄頁面

發(fā)布時間:2021-02-01 13:55:37 來源:億速云 閱讀:201 作者:小新 欄目:開發(fā)技術(shù)

小編給大家分享一下怎樣使用selenium和requests組合實現(xiàn)登錄頁面,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

一、在這里selenium的作用

(1)模擬的登錄。

(2)獲取登錄成功之后的cookies

代碼

def start_login(self):
  chrome_options = Options()
  # 禁止圖片加載,禁止推送通知
  prefs = {
    "profile.default_content_setting_values": {
      "images": 2
    }, "profile.default_content_setting_values.notifications": 2
  }
  chrome_options.add_experimental_option("prefs", prefs)
  if chrome_args().get("headless_flag") == "1":
    chrome_options.add_argument(chrome_args().get("headless"))
  chrome_options.add_argument(chrome_args().get("nogpu"))
  chrome_options.add_argument(chrome_args().get("noinfobars"))
  chrome_options.add_argument(chrome_args().get("max_windows"))
  chrome_options.add_argument(self.Proxy_server)
 
  driver = webdriver.Chrome(chrome_options=chrome_options)
  try:
    get_logger().info("start login.....")
    try:
      # login info
      self.login_name = self.loginInfo.get("login_id")
      self.password = aes_cbc_decrypt(self.loginInfo.get("login_pwd"))
    except Exception:
      get_logger().error("cant get login info,here are detals".format(traceback.format_exc()))
    wait = WebDriverWait(driver, 30)
    print(u"start login in")
    driver.get(self.login_url)
    try:
      login_id = wait.until(
        eccd.presence_of_element_located(
          (By.XPATH, self.Id_xpath))
      )
      login_id.send_keys(self.login_name)
      login_id.send_keys(Keys.ENTER)
      password = wait.until(
        eccd.presence_of_element_located(
          (By.XPATH, self.pwd_xpath))
      )
      password.send_keys(self.password)
      submit = wait.until(
        eccd.presence_of_element_located(
          (By.XPATH, self.login_btn_xpath))
      )
      submit.click()
      # login signal
      #判斷是否顯示 右上角是否顯示用戶名
      login_ok = wait.until(
        eccd.presence_of_element_located(
          (By.XPATH, self.login_ok_xpath))
      )
      try:
        #判斷登錄成功
        if login_ok:
          get_logger().info("get user name successful:"+u"{}".format(login_ok.text))
          try:
            get_weibo_info=driver.find_element_by_xpath(self.forward_home_page)
          except:
 
            driver.get(self.first_page)
 
          forward_home_page_ok = wait.until(
             eccd.presence_of_element_located(
               (By.XPATH, self.forward_home_page))
           )
          forward_home_page_ok.click()
          time.sleep(5)
          self.first_page=driver.current_url
          get_logger().info("get homepage successful,url is {}".format(driver.current_url))
          cookies = driver.get_cookies() # 導(dǎo)出cookie
          get_logger().info("get cookies")
          get_fansnum_ok= wait.until(
              eccd.presence_of_element_located(
                (By.XPATH, self.follow_xpath))
          )
          self.get_followfanshome(driver)
          get_logger().info("get_followfanshome ok")
          self.home_page_source=driver.page_source
          driver.close() # 關(guān)閉chrome
          #獲取主頁的
          # 如果需要保存cookies
          self.write_cookie(cookies)
          get_logger().info("get cookies,login ok")
          return cookies
 
 
        else:
          raise RuntimeError('login failed')
      except:
        get_logger().error("login failed")
        return None
 
    except:
      if driver is not None:
        driver.close()
  except Exception as e:
    if driver is not None:
      driver.close()
      get_logger().error("dbs operation error,here are details:{}".format(traceback.format_exc()))

通過使用cookies = driver.get_cookies() #我們獲取了cookie那么我們怎用呢。

二、requests如何使用獲取到的cookies

1.創(chuàng)建一個Session對象

req = requests.Session() # 構(gòu)建Session

2.轉(zhuǎn)換上面的cookies對象

for cookie in cookies:
      req.cookies.set(cookie['name'], cookie['value']) # 轉(zhuǎn)換cookies

3.開始訪問該網(wǎng)站的需求頁面

data = req.get(url, headers=self.headers).text #獲取文本網(wǎng)頁
jsondata = req.get(url, headers=self.headers).json() #獲取json型網(wǎng)頁

好了就是這么簡單,另外補充一個經(jīng)常使用的庫fake-useragent,可以獲取隨機的useragent,但是其中谷歌的useragent版本比較低,尤其在訪問知乎的時候,會提示瀏覽器版本低的信息,這一點需要注意。

另外擁有一個headers是對爬蟲起碼的尊重,所以有個構(gòu)建好的headers是非常必要的。我就經(jīng)常用下面的例:

from fake_useragent import UserAgent as UA
import random
 
headers = {
      'Accept': 'text/html, application/xhtml+xml, image/jxr, */*',
      'Accept - Encoding': 'gzip, deflate',
      'Accept-Language': 'zh-Hans-CN, zh-Hans; q=0.5',
      'Connection': 'Keep-Alive',
      'User-Agent': UA().random #獲取隨機的useragent
    }

看完了這篇文章,相信你對“怎樣使用selenium和requests組合實現(xiàn)登錄頁面”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI