2016-12-27 59 views
1

我嘗試使用下面的Python代碼刮痧部位與Python需要JavaScript的輸入

import re 
import requests 

def get_csrf(page): 
    matchme = r'name="csrfToken" value="(.*)" /' 
    csrf = re.search(matchme, str(page)) 
    csrf = csrf.group(1) 
    return csrf 

def login(): 
    login_url = 'https://www.edline.net/InterstitialLogin.page' 

    with requests.Session() as s: 
     login_page = s.get(login_url) 
     csrf = get_csrf(login_page.text) 

     username = 'USER' 
     password = 'PASS' 

     login = {'screenName': username, 
       'kclq': password, 
       'csrfToken': csrf, 
       'TCNK':'authenticationEntryComponent', 
       'submitEvent':'1', 
       'enterClicked':'true', 
       'ajaxSupported':'yes'} 
     page = s.post(login_url, data=login) 
     r = s.get("https://www.edline.net/UserDocList.page?") 
     print(r.text) 

login() 

此代碼登錄到https://www.edline.net/InterstitialLogin.page成功地刮的網站,但沒有當我嘗試做

r = s.get("https://www.edline.net/UserDocList.page?") 
print(r.text) 

它不打印預期頁面,而是拋出錯誤。經過進一步測試,我發現即使您嘗試從瀏覽器直接訪問該頁面,它也會拋出此錯誤。這意味着訪問頁面的唯一方法是運行單擊按鈕時執行的代碼。所以,當我調查頁面的源代碼,我發現用於鏈接到我試圖刮掉頁面的按鈕,使用下面的代碼

<a href="javascript:submitEvent('viewUserDocList', 'TCNK=headerComponent')" tabindex="-1">Private Reports</a> 

所以基本上我正在尋找一種方式來觸發JavaScript代碼之上python爲了颳去結果頁面。

+3

使用[selenium](http://selenium-python.readthedocs.io/getting-started.html),因爲它可讓您使用python以與瀏覽器用戶相同的方式與頁面進行交互。 – tihom

+0

在Chrome/Firefox中使用'DevTools'來查看當您單擊此按鈕時瀏覽器使用的值和URL。 – furas

+0

@furas在DevTools中,我應該查看/查看 –

回答

0

由於網站使用JavaScript,你需要像使用瀏覽器訪問頁面的硒之類的東西。以下代碼將與您的其他代碼一樣登錄到edline:

from selenium import webdriver 
import time 
driver = webdriver.Firefox() #any browser really 
url = 'https://www.edline.net/InterstitialLogin.page' 
driver.get(url) 
username_text = driver.find_element_by_xpath('//*[@id="screenName"]') #finds the username text box 
username_text.send_keys('username') #sends 'username' to the username text box 
password_text = driver.find_element_by_xpath('//*[@id="kclq"]') #finds the password text box 
password_text.send_keys('password') # sends 'password' to the password text box 
click_button = 
driver.find_element_by_xpath('/html/body/form[3]/div/div[2]/div/div[1]/div[3]/button').click() #finds the submit button and clicks on it 

一旦您登錄,就可以獲得完整的預期頁面。使用Selenium文檔很容易找到它!如果您還有其他問題,請告訴我。

+0

有沒有辦法只做這個相同的事情,而沒有使它調出瀏覽器?不知怎的,我可以讓它在背景中做到嗎? –

+0

你不需要以其他方式做。如果你願意,你可以隱藏瀏覽器。 http://stackoverflow.com/questions/16180428/can-selenium-webdriver-open-browser-windows-silently-in-background – titusAdam