我是python的新手。我真的很想知道如何从SELECT获取我的选项。在下面列出的情况下,我想选择SELECT标记的第一个选项。
我尝试了很多方法,但是都失败了。当前错误为“元素当前不可见,可能无法操作”。使用索引他们没有错误,但是什么也没显示
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
import time
driver = webdriver.PhantomJS(executable_path = r"C:\Users\dongyx\Downloads\phantomjs-2.1.1-windows\bin\phantomjs")
driver.implicitly_wait(15)
driver.get("https://studentcare.scse.ntu.edu.sg/sc1/f4_pt_pubass_attendance.php")
driver.set_window_size(1920, 1080)
driver.find_element_by_id("UID").send_keys("dong0096")
driver.find_element_by_name("PWORD").send_keys("Boris@21")
driver.find_element_by_name("SUBMIT").click()
time.sleep(3)
#print(driver.page_source.encode('utf-8').decode())
driver.get("https://studentcare.scse.ntu.edu.sg/sc1/f4_pt_pubass_attendance.php")
print(driver.page_source.encode('utf-8').decode())
driver.find_element_by_name('FilterBy')
sele_obj = driver.find_element_by_name('FilterBy')
select = Select(sele_obj)
for opt in select.options:
print(opt.get_attribute("index"))
print(select.options[1])
select._setSelected(select.options[1])
#select.select_by_index("1")
all_submits = driver.find_elements_by_xpath("//input[@name='SUBMIT']")
print(all_submits[0].get_attribute('name'))
all_submits[0].submit()
print(driver.page_source.encode('utf-8').decode())
没有打印源代码的输出是这样的:
0
1
2
3
4
5
6
7
8
selenium.webdriver.remote.webelement.WebElement (session="c7025190-d49e-
11e9-941d-a713501df08a", element=":wdc:1568211407446")
这是网站的源代码
<!DOCTYPE html>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<link rel="stylesheet" href="css/scheduler.css" />
<link rel="stylesheet" href="css/print.css" media="print" />
<link rel="stylesheet" href="sddmenu/sddmenu.css" />
<!-- <link rel="stylesheet" href="ddmenu/ddmenu.css" /> -->
<div class='center_header_div'><div id='ui_staff_header_container'><div id='ui_header_title_container'><p id='ui_header_title1'>NTU SCSE STUDENT CARE SYSTEM</p><p id='ui_header_title2'> </p></div></div></div><div class='ui_nav_container'><p id='ui_nav_left'>Welcome <b>Dong Yunxing</b> (Last Login: 2019-09-11 14:51:55)</p><p id='ui_nav_right'><a href='form_welcome.php'> Main </a> |
<a href='form_help.php'> Contact Us </a> |
<a href='logout.php'> Logout </a></p></div>
<noscript>
<div style="text-align:center; width:100%;">
<div style="margin:auto; text-align:center; color:red">
This site is best viewed with Javascript. Please turn on Javascript to use this site.
</div>
</div>
</noscript>
<head>
<link rel="stylesheet" href="jqueryui/css/redmond/jquery-ui-1.10.3.custom.min.css" />
<script src="js/jquery-1.10.2.js" type="text/javascript"></script>
<script src="jqueryui/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="chosen/chosen.css" />
<script src="chosen/chosen.jquery.min.js" type="text/javascript"></script>
<link rel="stylesheet" href="colorbox/colorbox.css" />
<script src="colorbox/jquery.colorbox-min.js" type="text/javascript"></script>
<link rel="stylesheet" href="tablesorter/themes/style.css" />
<script src="tablesorter/jquery.tablesorter.js" type="text/javascript"></script>
<script src="datetime/jquery-ui-timepicker-addon.js" type="text/javascript"></script>
<style>
div.ui-datepicker{
font-size:12px;
}
/* css for timepicker */
.ui-timepicker-div .ui-widget-header { margin-bottom: 8px; }
.ui-timepicker-div dl { text-align: left; }
.ui-timepicker-div dl dt { float: left; clear:left; padding: 0 0 0 5px; }
.ui-timepicker-div dl dd { margin: 0 10px 10px 45%; }
.ui-timepicker-div td { font-size: 90%; }
.ui-tpicker-grid-label { background: none; border: none; margin: 0; padding: 0; }
.ui-timepicker-rtl{ direction: rtl; }
.ui-timepicker-rtl dl { text-align: right; padding: 0 5px 0 0; }
.ui-timepicker-rtl dl dt{ float: right; clear: right; }
.ui-timepicker-rtl dl dd { margin: 0 45% 10px 10px; }
</style>
<script>
/*
$(function() {
$( "#Date1" ).datepicker({ defaultDate: "+1w", minDate: +1, maxDate: "+1M +1D" });
});
*/
$(function() {
$('[name="FilterBy"]').chosen({ search_contains:true });
$( "#Date1" ).datepicker({ minDate: '-120d', maxDate: '+120d', dateFormat: 'yy-mm-dd', altFormat: 'yy-mm-dd', altField: '#Date1' });
$( "#Date2" ).datepicker({ minDate: '-120d', maxDate: '+121d', dateFormat: 'yy-mm-dd', altFormat: 'yy-mm-dd', altField: '#Date2' });
$('.datepick').each(function(){ $(this).datetimepicker( {minDate: '-14d', maxDate: '+120d', dateFormat: 'yy-mm-dd'} ); $(this).attr('readOnly', 'true'); });
//$('.datepick').each(function(){ $(this).datetimepicker('setDate', new Date()); });
});
display_alert = false;
function toggle(source) {
//checkboxes = document.getElementsByName('delpub');
checkboxes = $("input:checkbox");
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
function Save_Only(event) {
//var eid = $(event.target).attr('id');
var eid = event.id;
if(display_alert) { alert("Called by " + eid); }
sign_attend(eid);
}
function Attend(event) {
//var eid = $(event.target).attr('id');
var eid = event.id;
if(display_alert) { alert("Called by " + eid); }
var eid_arr = eid.split("_");
var type = eid_arr[0];
var cid = eid_arr[1];
var sid = eid_arr[2];
var rid = eid_arr[3];
schedule_class_attend(eid);
var allid = cid + "_" + sid + "_" + rid;
document.getElementById("Remarks_" + allid).disabled = true;
document.getElementById("attend_" + allid).disabled = true;
}
function schedule_class_attend(event){
var eid = event;
if(display_alert) { alert("Called by " + eid); }
var eid_arr = eid.split("_");
var type = eid_arr[0];
var cid = eid_arr[1];
var sid = eid_arr[2];
var rid = eid_arr[3];
var allid = cid + "_" + sid + "_" + rid;
var S_Remarks = document.getElementById("Remarks_" + allid).value;
$.ajax({
type: "POST",
url: "btnajax_pt_pubass_attendance.php",
data: {
"Selected_Remarks": S_Remarks,
"Selected_Type": type,
"Selected_CID": cid,
"Selected_SID": sid,
"Selected_RID": rid,
},
dataType: "text",
success: function(responseData) {
var rpd = responseData.trim();
//alert("Response: [" + rpd + "]");
if(rpd >= 1){
document.getElementById("Status_" + type + "_" + allid).innerHTML = "ok";
//alert("Records Stored");
}else{
document.getElementById("Status_" + type + "_" + allid).innerHTML = rpd;
//alert("Error Found");
}
}
});
}
$(document).ready(function()
{
$("#SortThisTable").tablesorter();
/*
$("#SortThisTable").tablesorter({
headers: {
// assign the secound column (we start counting zero)
1: {
// disable it by setting the property sorter to false
sorter: false
},
}
});
*/
}
);
</script>
</head>
<!-- <p></p> -->
<!-- <h2>Welcome</h2> -->
<p></p>
<div class="center_menu_div">
<ul id="nav" class="drop">
<li>Forms
<ul>
<li><a href="create_new_tutee.php" target="_blank">Register for Peer Teaching Support as a Tutee</a></li>
<li><a href="create_new_tutor.php" target="_blank">Register for Peer Teaching Support as a Tutor</a></li>
<li><a href="create_new_coach.php" target="_blank">Register for Peer Teaching Support as a Coach</a></li>
<li><a href="create_new_feedback.php" target="_blank">Send Feedback</a></li>
<li><a href="create_new_counsellee.php" target="_blank">Register for counseling with SCSE Student Care</a></li>
<li><a href="create_new_alumni.php" target="_blank">Register as SCSE Alumni</a></li>
</ul>
</li>
<li>Publication Assignment (Tutoring)
<ul>
<li><a href="f4_pt_pubass_new_schedule.php">Create Class Schedule</a></li>
<li><a href="f4_pt_pubass_attendance.php">Mark Attendance</a></li>
<li><a href="f4_pt_pubass_mucl.php">Meetup Coordinator Log</a></li>
</ul>
</li>
</ul>
</div>
<div class="center_div">
<p></p>
<h2 style="padding-right:20px; border-bottom:1px solid black; position:relative; width:1400px; color: #606060; ">Mark Attendance</h2>
<h3 style='color: #989898;'>Please enter the following information:</h3>
<form action="/sc1/f4_pt_pubass_attendance.php" METHOD="POST">
<br>
<span style='font-size:8px;'> E-SignatureX: 77777777<br>(<i>As of 2019/09/11 03:39 pm</i>)</span><br><br>
<table style='width:1700px;'>
<tr>
<td style='width:154px;text-align:right;font-size:13px;'>Select Type <font color='red'>*</font> </td>
<td style='padding:4px 0px 7px 0px;'>
<SELECT name="FilterBy" style="width: 1110px;">
<option value=""></option>
<option value='2019-1-18-130-76-580'>[2019-1-18-130-76-580] AY 2019-2020 Semester 1 CE1011/CZ1011 ( Engineering Mathematics I ) 20190911 from 1830 to 2030</option><option value='2019-1-18-130-76-581'>[2019-1-18-130-76-581] AY 2019-2020 Semester 1 CE1011/CZ1011 ( Engineering Mathematics I ) 20190918 from 1830 to 2030</option><option value='2019-1-18-130-76-582'>[2019-1-18-130-76-582] AY 2019-2020 Semester 1 CE1011/CZ1011 ( Engineering Mathematics I ) 20190925 from 1830 to 2030</option><option value='2019-1-18-130-76-583'>[2019-1-18-130-76-583] AY 2019-2020 Semester 1 CE1011/CZ1011 ( Engineering Mathematics I ) 20191009 from 1830 to 2030</option><option value='2019-1-18-130-76-584'>[2019-1-18-130-76-584] AY 2019-2020 Semester 1 CE1011/CZ1011 ( Engineering Mathematics I ) 20191016 from 1830 to 2030</option><option value='2019-1-18-130-76-585'>[2019-1-18-130-76-585] AY 2019-2020 Semester 1 CE1011/CZ1011 ( Engineering Mathematics I ) 20191023 from 1830 to 2030</option><option value='2019-1-18-130-76-586'>[2019-1-18-130-76-586] AY 2019-2020 Semester 1 CE1011/CZ1011 ( Engineering Mathematics I ) 20191030 from 1830 to 2030</option><option value='2019-1-18-130-76-587'>[2019-1-18-130-76-587] AY 2019-2020 Semester 1 CE1011/CZ1011 ( Engineering Mathematics I ) 20191106 from 1830 to 2030</option> </SELECT>
</td>
</tr>
<tr>
<td style='width:154px;text-align:right;font-size:13px;'> </td>
<td></td>
</tr>
<tr>
<td style='width:154px;text-align:right;font-size:13px;'> </td>
<td>
<input type="submit" name="SUBMIT" value="Proceed"></input>
<input type="submit" name="SUBMIT" value="Export to Excel"></input>
</td>
</tr>
<tr>
<td style='width:154px;text-align:right;font-size:13px;'> </td>
<td></td>
</tr>
</table>
<table style='width:1700px;'>
</table>
</form>
</div>
我注意到实际上它设法检测出select的所有8个选项,但是只是在尝试更新该选项时发生了一些错误。
更具体地说,错误是(如果有用但很难读)
Message: {"errorMessage":"Element is not currently visible and may not be manipulated","request":{"headers":{"Accept":"application/json","Accept-Encoding":"identity","Content-Length":"81","Content-Type":"application/json;charset=UTF-8","Host":"127.0.0.1:51498","User-Agent":"selenium/3.141.0 (python windows)"},"httpVersion":"1.1","method":"POST","post":"{\"id\": \":wdc:1568211407446\", \"sessionId\": \"c7025190-d49e-11e9-941d-a713501df08a\"}","url":"/click","urlParsed":{"anchor":"","query":"","file":"click","directory":"/","path":"/click","relative":"/click","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/click","queryKey":{},"chunks":["click"]},"urlOriginal":"/session/c7025190-d49e-11e9-941d-a713501df08a/element/:wdc:1568211407446/click"}}
屏幕截图:可通过屏幕查看
我真的很奇怪为何_setSelected在这里不能工作,从回溯来看,它试图执行Command.CLICK_ELEMENT
时会产生异常。是因为我想先单击选择标签,然后才能显示所有选项
被点击?
答案 0 :(得分:0)
关于您正在使用的Select()函数,您的代码对我来说看起来不错。因此,当我查看错误消息时,它正在(可能)提供解决方案的提示。它找不到(在脚本中的该点/及时)要查找的元素。
由于您还没有(让)webdriver等待元素,因此,webdriver的速度可能比DOM快,或者特定元素可以拉起。
我建议您尝试等待元素解决此问题。
有多种等待元素的方法。
方法1(隐式等待):
您告诉它轮询DOM最长时间(以秒为单位)。当找不到所需的元素时,它将引发NoSuchElementException。
您可以在定义网络驱动程序后在脚本顶部执行此操作:
driver = webdriver.PhantomJS(executable_path = r"C:\Users\dongyx\Downloads\phantomjs-2.1.1-windows\bin\phantomjs")
driver.implicit_wait(15)
方法2(明确等待):
尤其要等待特定的元素。我们告诉它等待直到满足某些特定条件(为此,我们使用排除条件)
注意:为此,您需要导入一些额外的模块。
示例:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
men_menu = wait.until(EC.visibility_of_element_located((By.XPATH, "//a[@data-tracking-id='men']")))
fastrack = WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.XPATH, "//a[@data-tracking-id='0_Fastrack']")));
查看有关“等待”的文档:https://selenium-python.readthedocs.io/waits.html
请让我知道“等待”是否有助于解决您的问题!