简体   繁体   中英

Login to page with Selenium and Python

I have a website and I promise no one can log in to it with selenium here you are: https://edu.usc.ac.ir/Forms/AuthenticateUser/main.htm

This page has a different code from what you see, and I would like to crawl it with Selenium.

I write the below code :

from selenium import webdriver
import time
url = "https://edu.usc.ac.ir/Forms/AuthenticateUser/main.htm"
driver = webdriver.Chrome('chromedriver.exe')
driver.get(url)
time.sleep(5)
username = driver.find_element_by_id("F80351")
password = driver.find_element_by_id("F80401")

When I use this code I get this error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"id","selector":"F80351"}``

I can't figure out why it can't find the element that exists in this page.

If you look closely at the document, you'll see it's comprised of several frames stacked upon each other.

<body ...>
    ...
    <div id="FacArea" style="top: 48px; position: absolute; overflow: hidden; width: 672px; height: 572px;">
        <div style="overflow: auto; position: absolute; z-index: 2; width: 672px; height: 572px;">
            <iframe src="nav.htm?fid=0;1&amp;tck=&amp;" id="Faci1" name="Faci1" width="672" height="572" style="z-index: 2;">
                #document
                <html>
                    ...
                </html>
            </iframe>
        </div>
    </div>
    ...
</body>

Your username and password input are located in a document 3 frames deep, which is why you can't find them. You need to iteratively find those frames and switch to them.

driver = webdriver.Chrome('chromedriver.exe')
driver.get(url)

frame_names = ('Faci1', 'Master', 'Form_Body')
for name in frame_names:
    frame = driver.find_element_by_name(name)
    driver.switch_to_frame(frame)

username = driver.find_element_by_id('F80351')
password = driver.find_element_by_id('F80401')

Your problem is that you're not doing anything with the elements that you've found.

Change:

username = driver.find_element_by_id("F80351")
password = driver.find_element_by_id("F80401")

To:

driver.find_element_by_id("F80351").send_keys('your username')
driver.find_element_by_id("F80401").send_keys('your password')
driver.find_element_by_id("btnLog").click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM