我正在运行一个执行以下操作的Python脚本:
- 打开网页
- 使用登录表单登录游戏
- 等待页面加载(获取Ajax请求的Json响应(
- 点击几下
- 单击触发ajax请求的按钮
- 需要读取Ajax请求的json响应<这就是我的问题所在
- 写入文件
我的问题是,我无法捕捉到第二轮Ajax请求,在谷歌上搜索时也找不到任何解决方案。
我的代码是这样的:
import sys
import json
import time
from seleniumwire import webdriver # Import from seleniumwire
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
from selenium.webdriver import ActionChains
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
binary = FirefoxBinary(r'C:\Program Files\Mozilla Firefox\firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary)
driver.get(myURL)
# Login code here
loginButton = driver.find_element_by_id('login_Login')
loginButton.click();
for request in driver.requests: # Initial page loading
if "login_check" in request.path:
if request.response:
response_body = json.loads(request.response.body)
for key, value in response_body.items():
if key == 'success':
if value is False:
# do some stuff and write to file
#driver.quit()
break
else:
defaultContent_switched = driver.switch_to.default_content()
try:
# do some stuff and write to file
except TimeoutException:
canvas = driver.find_element_by_tag_name('canvas')
canvas.click();
#click on a few elements
for request in driver.requests:
if "/game/json" in request.path:
print(request.path); # At this point I only see the requests of the initial load of the page
if request.response:
# Need to do stuff here...
break
break
break
print(json.dumps(output))
driver.quit()
单击画布后,如何重新开始收听网络?
只要有页面加载或一些内容加载,就可以使用下面的Ajax加载函数来等待Ajax加载完成。
#Wait webpage to fully load
def ajaxwait():
for i in range(1, 30):
x = driver.execute_script("return (window.jQuery != null) && jQuery.active")
time.sleep(1)
if x == 0:
print("All Ajax element loaded successfully")
break