我正在学习python并尝试修复现有代码。
该脚本打开一个页面,单击“接受”按钮。我相信这很好用。但是,该网站现在显示javascript
提醒,我需要接受该提醒。
经过大量挖掘并尝试使用其他帖子的建议后,我创建了以下代码(我无法将其全部发布,但这应该是相关部分):
from bs4 import BeautifulSoup
import datetime
import getpass
from gmail import Gmail
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementNotVisibleException
from selenium.common.exceptions import NoAlertPresentException
from time import sleep
#code block
self.chrome_session = webdriver.PhantomJS()
#code block
for link_text, link_url in links:
print("{0}: Clicking work order {1}.".format(datetime.datetime.now(),link_text))
self.chrome_session.get(link_url)
print("{0}: Attempting to accept".format(datetime.datetime.now()))
try:
potential_input = self.chrome_session.find_element_by_xpath(
"//input[@value='Accept']"
)
sleep(1)
potential_input.click()
print("{0}: Accept clicked.".format(datetime.datetime.now()))
sleep(5)
try:
alert = self.chrome_session.switch_to.alert
print "Alert found"
print alert
alert.accept()
print("{0}: Accepted work order {1}.".format(
datetime.datetime.now(),link_text
))
except NoAlertPresentException:
print "Alert not found"
except Exception as inst:
print type(inst)
print inst.args
print inst
print("{0}: Accept input not found.".format(datetime.datetime.now()))
self.chrome_session.back()
该脚本一直有效,直到alert.accept()
。
警告会显示两个按钮:Ok
和Cancel
。
我试过了:
alert = self.chrome_session.switch_to().alert
alert = self.chrome_session.switch_to().alert()
alert = self.chrome_session.switch_to.alert
最近似乎是最接近的。但是,当它到达alert.accept()
时,会抛出以下错误:
<selenium.webdriver.common.alert.Alert object at 0x7fface9de1d0>
<class 'selenium.common.exceptions.WebDriverException'>
()
Message: Invalid Command Method - {"headers":{
"Accept":"application/json",
"Accept-Encoding":"identity",
"Connection":"close",
"Content-Length":"53",
"Content-Type":"application/json;charset=UTF-8",
"Host":"127.0.0.1:55633",
"User-Agent":"Python http auth"},
"httpVersion":"1.1",
"method":"POST",
"post":"{\"sessionId\": \"94d3c650-ce28-11e7-a11e-17604cd282eb\"}",
"url":"/accept_alert",
"urlParsed":"anchor":"",
"query":"",
"file":"accept_alert",
"directory":"/",
"path":"/accept_alert",
"relative":"/accept_alert",
"port":"",
"host":"",
"password":"",
"user":"",
"userInfo":"",
"authority":"",
"protocol":"",
"source":"/accept_alert",
"queryKey":{},
"chunks":["accept_alert"]},
"urlOriginal":"/session/94d3c650-ce28-11e7-a11e-17604cd282eb/accept_alert"}
如何识别警报并接受警报?
更新
似乎javascript
警报未随脚本打开。我不确定它是否有所作为,但我在警报之前点击的“接受”按钮如下:
<input type="button" class="btn btn-primary" value="Accept"
onclick="javascript:updateAcceptorRejectFlag(1)" style="display: inline-block;">
我是否可能无法正确调用它,因此警报实际上并未显示?