Выход из Сайта работает должным образом./ Если сайт не загружается, закройте браузер и снова откройте - PullRequest
1 голос
/ 28 апреля 2019

Итак, я написал скрипт на Python, который входит в учетную запись, собирает некоторую валюту и выходит из системы, и он просматривает множество учетных записей.Это легко скрипт для сбора этой валюты с тоннами счетов.Проблема в том, что каждый раз, когда скрипту нужно выйти из системы, он нажимает кнопку «Выйти», но если он снова попадает на страницу регистрации, он говорит, что он все еще вошел в систему.Кстати, иногда сайт загружается, а сценарий просто закрывается. Кто-нибудь знает, как реализовать функцию, которая перезагружает страницу или повторно открывает хроматический драйвер?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import traceback
from time import sleep 

browser = webdriver.Chrome(executable_path='C:\\Users\klime\Desktop\Python Palai Bot\chromedriver')
wait = WebDriverWait(browser, 30)
lines = open('acc.txt', 'r').read().split('\n')

for l in lines:
    try:

        print("Trieng to connect to Palai.org")
        browser.get('https://www.palai.org/u/sign_in')
        print("Successfully connected to Palai.org!")

        print("Trieng to Log into the Account: ", l)
        email = wait.until(EC.visibility_of(browser.find_element_by_id("user_email")))
        email.send_keys(l)

        password = wait.until(EC.visibility_of_element_located((By.ID,"user_password")))
        password.send_keys("mypassword")

        commit = wait.until(EC.visibility_of(browser.find_element_by_name('commit')))
        commit.click()
        print("Successfully logged in!")

        collect = wait.until(EC.visibility_of(browser.find_element_by_link_text('Abholen')))
        collect.click()

        collectTwo = wait.until(EC.visibility_of(browser.find_element_by_xpath('//*[@id=\"app\"]/article/div[1]/div/div/div/div[1]/div/div/form/input[1]')))
        collectTwo.click()
        print("Successfully collected Palai")

        print("Transfering...")
        browser.get('https://palai.org/a/kliment+843fb7f2d-f17f-4f86-8365-0aeaf61f566e/pay?transfer_amount=176PALAI')

        email = wait.until(EC.visibility_of(browser.find_element_by_id("user_email")))
        email.send_keys(l)

        password = wait.until(EC.visibility_of_element_located((By.ID,"user_password")))
        password.send_keys("mypassword")

        commit = wait.until(EC.visibility_of(browser.find_element_by_name('commit')))
        commit.click()
        print("Successfully logged in now Transfering Palai...")

        submit = wait.until(EC.visibility_of(browser.find_element_by_id('submit_transfer')))
        submit.click()
        print("Successfully transferd the Palai to the Main Account!")

        print("Logging out...")
        logout = wait.until(EC.visibility_of(browser.find_element_by_css_selector("form.button_to > button")))
        logout.click()
        sleep(10)
        print("Successfully logged out of the Account!")

    except Exception as e:
        traceback.print_exc()
        browser.quit()

browser.quit()

Это ошибка, которую я получаю после

Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> 
========== RESTART: C:\Users\klime\Desktop\Python Palai Bot\Bot.py ==========
Trieng to connect to Palai.org
Successfully connected to Palai.org!
Trieng to Log into the Account:  thisismyemail@myemail.com
Successfully logged in!
Successfully collected Palai
Transfering...
Successfully logged in now Transfering Palai...
Successfully transferd the Palai to the Main Account!
Logging out...
Successfully logged out of the Account!
Trieng to connect to Palai.org
Successfully connected to Palai.org!
Trieng to Log into the Account:  thisismyemail2@myemail.com
Traceback (most recent call last):
  File "C:\Users\klime\Desktop\Python Palai Bot\Bot.py", line 21, in <module>
    email = wait.until(EC.visibility_of(browser.find_element_by_id("user_email")))
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 360, in find_element_by_id
    return self.find_element(by=By.ID, value=id_)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
    'value': value})['value']
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\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":"id","selector":"user_email"}
  (Session info: chrome=74.0.3729.108)
  (Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17763 x86_64)

Trieng to connect to Palai.org
Traceback (most recent call last):
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\connection.py", line 80, in create_connection
    raise err
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\util\connection.py", line 70, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [WinError 10061] Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connectionpool.py", line 354, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1229, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1275, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1224, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 1016, in _send_output
    self.send(msg)
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\http\client.py", line 956, in send
    self.connect()
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 181, in connect
    conn = self._new_conn()
  File "C:\Users\klime\AppData\Local\Programs\Python\Python37-32\lib\site-packages\urllib3\connection.py", line 168, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x0476D390>: Failed to establish a new connection: [WinError 10061] Es konnte keine Verbindung hergestellt werden, da der Zielcomputer die Verbindung verweigerte

Хорошо, сценарий должен нормально выйти из системы без каких-либо проблем, и, если браузер не загрузит страницу, браузер просто закроется и снова откроется.

1 Ответ

0 голосов
/ 28 апреля 2019

Кажется, ваш кодовый блок был почти идеальным. Поскольку вы пытаетесь отправить последовательность символов в нужные поля, вместо использования expected_conditions из visibility_of() вам необходимо использовать element_to_be_clickable() следующим образом:

print("Trieng to connect to Palai.org")
browser.get('https://www.palai.org/u/sign_in')
# WebDriverWait(browser, 10).until(EC.title_contains("Log in – Palai (beta)"))
print("Successfully connected to Palai.org!")

print("Trieng to Log into the Account: ", l)
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.ID, "user_email"))).send_keys(l)
browser.find_element_by_id("user_password").send_keys("mypassword")
browser.find_element_by_name('commit').click()
print("Successfully logged in!")
...