刮取需要身份验证的网站

时间:2016-08-26 09:46:47

标签: python

我知道这个问题可能看起来很简单,但我已经尝试了所有建议,但没有一个有效。

我想构建一个Python脚本,检查我的学校网站,看看是否已经提出了新的成绩。但是我不能为我的生活弄清楚如何刮掉它。

网站重定向到另一个页面进行登录。我已经尝试了所有可以找到的脚本和答案,但我迷失了。

我使用的是Python 3,该网站位于https://blah.schooldomate.state.edu.country/website/grades/summary.aspx 格式

用户名部分包含以下内容:

<input class="txt" id="username" name="username" type="text" autocomplete="off" style="cursor: auto;">

密码是名称,但它包含onfocus HTML元素。

一个成功通过身份验证后,我会自动重定向到正确的页面。

我试过了:

使用Python 2的cookielib和Mechanize

使用HTTPBasicAuth

将信息作为dict传递给requests.get()

尝试许多不同的人代码,包括我在本网站上找到的答案

2 个答案:

答案 0 :(得分:0)

您可以尝试处理请求: http://docs.python-requests.org/en/master/

来自网站:

import requests

r = requests.get('https://api.github.com/user', auth=('user', 'pass'))

答案 1 :(得分:0)

也许您可以使用Selenium库。

我告诉你我的代码示例:

from selenium import webdriver

def loging():
    browser = webdriver.Firefox()
    browser.get("www.your_url.com")

    #Edit the XPATH of Loging INPUT username
    xpath_username = "//input[@class='username']"  

    #Edit the XPATH of Loging INPUT password
    xpath_password = "//input[@class='password']"  

    #THIS will write the YOUR_USERNAME/pass in the xpath (Custom function)
    click_xpath(browser, xpath_username, "YOUR_USERNAME")  
    click_xpath(browser, xpath_username, "YOUR_PASSWORD")  

    #THEN SCRAPE WHAT YOU NEED

#Here is the custom function
#If NO input, will only click on the element (on a button for example)
def click_xpath(self, browser, xpath, input="", time_wait=10):
    try:
        browser.implicitly_wait(time_wait)
        wait = WebDriverWait(browser, time_wait)
        search = wait.until(EC.element_to_be_clickable((By.XPATH, xpath)))
        search.click()
        sleep(1)
        #Write in the element
        if input:
            search.send_keys(str(input) + Keys.RETURN)
        return search
    except Exception as e:
        #print("ERROR-click_xpath: "+xpath)
        return False
相关问题