Python、2个文件中的变量和selenium

2024-09-28 23:02:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了main.pylogin.py,然后尝试将这两个文件链接在一起。我不知道如何正确链接这两个文件。你知道吗

我使用的是selenium,程序可以运行,但它会打开两个chrome窗口(当我只想打开一个时),然后,第二个窗口继续运行,并且运行得很好,但是当它停止运行登录文件时,突然出现了以下错误:

Traceback (most recent call last):
File "C:/Users/alebu/PycharmProjects/selenium/Main.py", line 9, in <module>
Login.login()
File "C:\Users\alebu\PycharmProjects\selenium\Login.py", line 6, in login
Main.browser.find_element_by_link_text('Log in').click()
File "C:\Users\alebu\PycharmProjects\selenium\venv\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 419, in 
find_element_by_link_text
return self.find_element(by=By.LINK_TEXT, value=link_text)
File "C:\Users\alebu\PycharmProjects\selenium\venv\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 955, in find_element
'value': value})['value']
File "C:\Users\alebu\PycharmProjects\selenium\venv\lib\site-
packages\selenium\webdriver\remote\webdriver.py", line 312, in execute
self.error_handler.check_response(response)
File "C:\Users\alebu\PycharmProjects\selenium\venv\lib\site-
packages\selenium\webdriver\remote\errorhandler.py", line 242, in 
check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: 
Unable to locate element: {"method":"link text","selector":"Log in"}
(Session info: chrome=64.0.3282.167)
(Driver info: chromedriver=2.35.528161 
(5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 
x86_64)


Process finished with exit code 1

可能是我把变量弄错了 这个主.py你知道吗

from selenium import webdriver
import Login

driver_location = "C:\webDrivers\chromedriver.exe"
options = webdriver.ChromeOptions()
options.add_argument('--lang=en')
browser = webdriver.Chrome(executable_path=driver_location, 
chrome_options=options)
Login.login()

那个登录.py你知道吗

def login():
    import Main
    from time import sleep
    Main.browser.get('https://www.instagram.com')

    Main.browser.find_element_by_link_text('Log in').click()

    Main.browser.find_element_by_name('username').send_keys('*******')
    Main.browser.find_element_by_name('password').send_keys(********')

    Main.browser.find_element_by_xpath('//form/span/button[text()="Log 
    in"]').click()
    sleep(3)
    Main.browser.find_element_by_link_text('Not Now').click()
    sleep(2)
    print("Logged In")

奇怪的是:在程序出现在一个唯一的文件中之前,它工作得非常完美。你知道吗


Tags: textinpybrowserbymainseleniumline
1条回答
网友
1楼 · 发布于 2024-09-28 23:02:47

我建议您阅读一些关于import如何在python here中工作的资料。你知道吗

为了让您所拥有的能够快速正常工作,您不应该在您的登录函数中import Main。在login函数中尝试将驱动程序作为参数传递(注意:在将浏览器作为参数传递并且不导入Main之后,您将不再需要使用Main.browser,只需要browser):

from time import sleep
def login(browser):
    browser.get('https://www.instagram.com')

然后,当您从main调用login时,您需要将browser作为参数传递:

Login.login(browser)

这应该可以解决您在打开两个浏览器时遇到的问题。如果问题仍然存在,但没有找到Log in链接,请阅读this,如果您清楚地了解了它的工作原理,并且需要更多帮助,请提出一个新问题。你知道吗

相关问题 更多 >