使用 Python 自动登录到我的本地网页

Posted

技术标签:

【中文标题】使用 Python 自动登录到我的本地网页【英文标题】:Auto Login using Python to my local internet page 【发布时间】:2017-04-02 19:19:16 【问题描述】:

我有有线互联网,需要通过网页登录。每天早上 8 点和 12 点重置的方式很烦人。我想编写一个 python 脚本来自动化登录过程。到目前为止,我已经阅读了许多 *** 解决方案,但没有任何效果。我试过Requests、Twill、RoboBrowser等。

在检查页面源代码时,我发现了一个由登录按钮触发的 doLogin() ajax 脚本。这是完整的page source。

以下是我失败的实现之一

import requests

# Fill in your details here to be posted to the login form.
payload = 
    'action': 'http://10.10.0.1/login',
    'actualusername': 'username',
    'actualpassword': 'password'


# Use 'with' to ensure the session context is closed after use.
with requests.Session() as s:
    p = s.post("http://103.251.83.134/captiveportal/Default.aspx", data=payload)
    # print the html returned or something more intelligent to see if it's a successful login page.
    print p.text

    # An authorised request.
    #r = s.get('http://www.google.com')
    #print r.text

编辑:解决方案

我使用 Selenium WebDriver 来解决这个问题。检查答案。

【问题讨论】:

【参考方案1】:

使用 Selenium :) 将 ChromeDriver 下载到路径,创建一个两次变量并检查每分钟的时间。如果是“登录时间”,您的浏览器将通过授权。

from selenium import webdriver

def Authorization_for_broadband():
    driver = webdriver.Chrome("C:\YOURPATHTO\CHROMEDRIVER.EXE")

    driver.get('http://10.10.0.1/login')
    driver.find_element_by_xpath('//*[@id="username"]').send_keys('USERNAME')
    driver.find_element_by_xpath('//*[@id="password"]').send_keys('PASSWORD')
    driver.find_element_by_xpath('//*[@id="btnLogin"]').click()
    driver.close

while(1):
    if time=='your-login-period1' or time == 'your-login-period2':
        Authorization_for_broadband()

【讨论】:

我今天完全实现了这个,甚至在阅读这个答案之前!感谢您发布此信息。我使用了 webdriver.Firefox() 虽然。哪个工作正常。我希望这个过程保持沉默,因为我会在某处阅读时尝试 PhantomJS。如果有人需要,我会做出这个公认的解决方案!【参考方案2】:

您的网址可能有误。查看源代码,看起来 HTML 表单正在向http://10.10.0.1/login 页面发布数据,然后doLogin() 函数正在向Register.aspx?CheckCustomerStatus=1 提交数据。

您的有效负载还包含变量action,并且您正在使用Session 对象,我认为这没有必要。

我无法测试它,因为它是我无法访问的本地登录页面,但我会尝试修改您的代码以使用更简单的POST request 将登录信息提交到两个页面

【讨论】:

以上是关于使用 Python 自动登录到我的本地网页的主要内容,如果未能解决你的问题,请参考以下文章

python3实现自动登录网页版QQ

Visual Basic 19 - WebView2 - 自动单击网页按钮

交互式登录网站-自动以域用户登录的问题,求解决

跳转到另一个网页时自动登录

怎样用python实现网页自动登录?

Python +selenium 实现自动校园网页登录 (Firefox)