首頁  >  問答  >  主體

python - selenium 运行网页中js脚本报错,提示未定义

问题1

selenium 运行网易中js脚本报错提示未定义
报错提示如下:

driver.execute_script("javascript:amsInit(62800,303153);");

error:
selenium.common.exceptions.WebDriverException: Message: ReferenceError: amsInit is not defined

js函数是个链接,点击后打开天涯明月刀的选择服务器大区窗口,按钮的代码如下:

<a href="javascript:amsInit(62800, 303153);">【绑定大区】</a>

firefox控制台运行 amsInit(62800, 303153); 有效能正常打开选择大区窗口,但会提示未定义,如下:

firefox控制台运行

>>amsInit(62800,303153)
<-undefined

请问直接调用网页中的类似js脚本,需要如何实现?

问题2:

代码如下一个的一个选择窗口,如何用selenium操作

<li style="display:inline;" class="area_select_li"><select id="area1ContentId_wuxia"><option value="">请选择大区</option><option value="7609515">青龙乱舞</option><option value="7609516">大地飞鹰</option><option value="7609559">血海飘香</option><option value="7609560">名剑风流</option><option value="7609617">陌上花开</option><option value="7609705">天命风流</option></select><select id="areaContentId_wuxia"><option value="">请选择服务器</option></select></li>

尝试一下方法均不可选中

使用Select方法无效

Select(driver.find_element_by_id("area1ContentId_wuxia")).select_by_value("7609705")

遍历option,使用click方法无效

allOptions = select.find_elements_by_tag_name("option")
for option in allOptions:
    print "Value is: " + option.get_attribute("value") + "Text is:"+ option.text
    option.click()
    break


请问如上的选择应该如何操作?

天蓬老师天蓬老师2711 天前654

全部回覆(1)我來回復

  • 高洛峰

    高洛峰2017-04-18 09:50:28

    自己解決:
    這個選擇框是js回調操作的 select 方法和client都無效,解決方法是 使用 keys.ARROW_DOWN鍵盤事件模擬選擇

    # 遍历选择大区,服务器
        allarea1options = driver.find_element_by_id("area1ContentId_wuxia").find_elements_by_tag_name("option")        
        for option in allarea1options:
            if option.text == area1:
                print(u"找到大区:".encode("gbk") + option.text.encode("gbk"))
                driver.find_element_by_id("area1ContentId_wuxia").send_keys(Keys.ENTER)
                time.sleep(1)
                # 选择服务器
                select_area  = driver.find_element_by_id("areaContentId_wuxia")
                allareaoptions = select_area.find_elements_by_tag_name("option")
                for option in allareaoptions:
                    if option.text == area2:
                        print(u"找到服务器:".encode("gbk") + option.text.encode("gbk"))
                        driver.find_element_by_id("areaContentId_wuxia").send_keys(Keys.ENTER)
                        break
                    else:
                        driver.find_element_by_id("areaContentId_wuxia").send_keys(Keys.ARROW_DOWN)
            else:
                driver.find_element_by_id("area1ContentId_wuxia").send_keys(Keys.ARROW_DOWN)

    回覆
    0
  • 取消回覆