【问题标题】:Scraping a website that requires authentication抓取需要身份验证的网站
【发布时间】:2017-01-02 22:51:43
【问题描述】:

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

我想构建一个 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()

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

【问题讨论】:

  • 你可以认证吗?如果是这样,您必须使用 python 请求遵循重定向并使用 session 来存储 cookie
  • 最简单的方法是使用 chrome 登录,然后从开发工具中获取 cURL url,然后进行操作。

标签: python


【解决方案1】:

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

来自网站:

import requests

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

【讨论】:

    【解决方案2】:

    也许你可以使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      • 1970-01-01
      • 1970-01-01
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多