我有以下类型的 HTML 代码可供使用:
<tbody id="id_tbody">
<tr id="tr_project_0" class="project_tr clr01 hover" data-select-value="0" style="border-top: 1px dotted #B4B4B4;">
<td class="txtC">
<a href="/173537">173537</a>
</td>
<tr id="tr_research_0" style="" class="">
<table id="table_project_num_173537" class="tblTypeInner01 cl_tr_research_node">
<tbody>
<tr id="tr_research_node_173537_0" class="research_tr" data-select-value="442879,0,173537,2">
<td class="txtC"><a href="/442879">442879</a></td>
以及以下 Python 代码:
project_list = browser.find_element_by_xpath( "//tr[@class='project_tr clr01']" )
survey_list = project_list.find_elements_by_xpath( "//tr[@class='research_tr']" )
last_survey = survey_list[0]
survey_go = last_survey.find_elements_by_xpath( "//td[@class='txtC']" )
print survey_go[0].text
我期望脚本返回“442879”
,但它返回“173537”
。
为什么 survey_go
返回 project_list
的子元素而不是 survey_list[0]
?
最佳答案
您需要指定 XPath 开头的点以指向上下文节点 (project_list
):
survey_list = project_list.find_elements_by_xpath( ".//tr[@class='research_tr']" )
与survey_go
相同:
last_survey = survey_list[0]
survey_go = last_survey.find_elements_by_xpath( ".//td[@class='txtC']" )
关于python - 在Python中使用Selenium选择子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53702083/