在Python中使用Selenium选择子元素

时间:2018-12-10 08:43:17

标签: python html selenium xpath

我可以使用以下类型的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]的子元素?

1 个答案:

答案 0 :(得分:0)

您需要在XPath的开头指定点以指向上下文节点(one record):

How to Format<br>
How to Code<br>
How to Debug<br>
How to Test<br>
and more

project_list相同:

survey_list = project_list.find_elements_by_xpath( ".//tr[@class='research_tr']" )