警报上的Python单击按钮

编程入门 行业动态 更新时间:2024-10-26 00:22:34
本文介绍了警报上的Python单击按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是python的新手,但需要修改其他人创建的代码.我无法发布完整的代码,但是我在下面发布了大部分代码:

I am new to python, but need to modify code created by someone else. I am not able to post the full code, but I posted most of it below:

from bs4 import BeautifulSoup import datetime import getpass from gmail import Gmail from selenium import webdriver from seleniummon.exceptions import NoSuchElementException from seleniummon.exceptions import ElementNotVisibleException from time import sleep from seleniummon.exceptions import NoAlertPresentException from selenium.webdriver.support import expected_conditions as EC def soupify(session, url): """ Makes parse-able HTML from any given URL. :param session: requests.Session() :param url: str :return: BeautifulSoup object """ while True: try: r = session.get(url) break except Exception as e: print(e) return BeautifulSoup(r.content, 'html.parser') def create_http_session(): """ Quick little function for returning a requests.Session() instance with a properly set User-Agent header. :return: requests.Session() """ session = requests.Session() session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' }) return session def retrieve_hidden_input(soup, name): return soup.find('input', attrs={ 'type': 'hidden', 'name': name }).get('value') class AmericanHomesScraper: def __init__(self, username, password, testing): self.username = username self.password = password self.testing = testing self.chrome_session = webdriver.PhantomJS() self.chrome_session.maximize_window() self.g = Gmail() self.g.login(username, password) self.index = 0 def check_for_new_emails_from_sender(self, sender='info@mailerflix'): self.index += 1 if self.index % 1000 == 0: print('Checking emails - {0}.'.format(datetime.datetime.now())) elif self.index == 1: print('Checking emails - {0}.'.format(datetime.datetime.now())) else: pass for s in sender: messages = self.g.inbox().mail(sender=s, unread=True) for message in messages: message.read() print( 'Email from {0}: {1}.'.format(s, datetime.datetime.now())) self.check_for_listings() self.g.logout() self.g = Gmail() self.g.login(self.username, self.password) def login(self, username, ahsPassword): self.ahsPassword = ahsPassword self.chrome_session.get('www.aaa/Login.aspx') self.chrome_session.find_element_by_xpath( '//*[@id="txtUsername"]' ).send_keys(username) self.chrome_session.find_element_by_xpath( '//*[@id="txtPassword"]' ).send_keys(ahsPassword) self.chrome_session.find_element_by_xpath( '//*[@id="btnSubmit"]' ).click() def check_for_listings(self): #code block links = self.chrome_session.find_elements_by_class_name('link-record') links = [(link.text, link.get_attribute('href').decode('utf-8')) for link in links] if len(links) == 0: print("No work orders available at {0}".format( datetime.datetime.now()) ) else: for link_text, link_url in links: print("Clicking work order {0} at {1}".format(link_text,datetime.datetime.now())) self.chrome_session.get(link_url) print("Attempting to accept at {0}".format(datetime.datetime.now())) try: self.chrome_session.find_element_by_xpath("//input[@value='Accept']").click() try: WebDriverWait(self.chrome_session, 1).until(EC.alert_is_present) self.chrome_session.switch_to().alert().accept() print("Accepted work order {0} at {1}.".format(link_text,datetime.datetime.now())) except: print "no alert" except ElementNotVisibleException: print("Accept input not found at {0}".format(datetime.datetime.now())) self.chrome_session.back() def main(): username = raw_input( 'Please enter the username of the GMail account you want to monitor.\n>') password = getpass.getpass( 'Please enter the password of the GMail account you want to monitor.\n>') ahsPassword = getpass.getpass('Please enter the password for ahs. \n>') ahs = AmericanHomesScraper(username, password, testing) ahs.login(username,ahsPassword) print("Starting script") while True: ahs.check_for_new_emails_from_sender([ 'crm@aaa', 'ds@aaa', ]) if __name__ == '__main__': main()

这可以正确找到并单击接受"输入按钮.单击接受后,将打开一个JavaScript警报(确定/取消)以确认接受.但是,该脚本找不到找到的警报.或者,至少它不能接受它,因为调用了异常.

This correctly finds and clicks the "Accept" input button. After clicking accept, a javascript alert (Ok/Cancel) opens to confirm the acceptance. However, the script does not find the resulting alert. Or, at least it is not able to accept it because the exception is called.

如您所见,我已经尝试了switch_to().alert(),但这没有用.

As you can see, I have attempted to switch_to().alert(), but that isn't working.

我做错了什么?非常感谢您的帮助,我已经为此工作了几个小时.

What am I doing wrong? Thank you so much for your help, I have been working on this for hours.

更新

此代码在虚拟服务器上运行,并且不使用UI.我只是意识到驱动程序是PhantomJS,而不是Chrome.因此,这可能就是失败的原因.我已经更新了问题以反映这一点.

This code is running on a virtual server and does not use a UI. I just realized that the driver is PhantomJS, not Chrome. So, this is probably why it is failing. I have updated the question to reflect this.

我已经尝试过类似问题的建议,但是它不起作用.第三方站点需要警报确认才能完成该过程,但是我的脚本看不到它,因为它没有头.

I have tried the suggestions from similar questions, but it isn't working. The 3rd party site requires the alert confirmation to finish the process, but my script cannot see it because it is headless.

推荐答案

这里有几点:

  • switch_to_alert 已被弃用,因此我们必须强制使用 switch_to().alert()
  • 对我来说似乎是一个纯粹的计时问题.因此,我们需要使用 expected_conditions 子句设置为 alert_is_present 的 ExplicitWait 即 WebDriverWait 如下:

  • switch_to_alert had been deprecated so we have to mandatory use switch_to().alert()
  • Seems to me a purely timing issue. Hence we need to induce ExplicitWait i.e. WebDriverWait with expected_conditions clause set to alert_is_present as follows :

from selenium.webdriver.support import expected_conditions as EC #code block self.chrome_session.find_element_by_xpath("//input[@value='Accept']").click() WebDriverWait(self.chrome_session, 10).until(EC.alert_is_present) self.chrome_session.switch_to().alert().accept() print("Accepted work order {0} at {1}.".format(link_text, datetime.datetime.now()))

更多推荐

警报上的Python单击按钮

本文发布于:2023-11-27 15:51:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1638634.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:警报   单击   按钮   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!