python - 在Python中使用Selenium选择子元素

标签 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]

最佳答案

您需要指定 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/

相关文章:

python - 我应该使用哪种数据结构进行地理编码?

php - Android phonegap 使用本地 html 和远程 php 登录

python - 无法使用selenium从页面中名为 'heading'的每个类获取数据

python - 如何使用pipreqs创建requirements.txt文件

python - 从新手到专业的Python代码不起作用

javascript - jQuery 日期选择器 : highlight and style multiple dates

javascript - 带有 JavaScript 的 Html5 音频无法在 Chrome 以外的任何浏览器中运行

java - 可以覆盖@FindBy 的父类(super class)

Selenium IDE 从 URL 加载套件和测试用例?

selenium - 如何使用 Selenium 设置 Chrome 代理的用户名和密码?