我首先尝试使用.find_elements_by_xpath选择网站上的所有菜单项。这很好用
(按钮为文字或图像)。
然后我想遍历每个元素,并返回标记之间的文本或span标记图像的src,该标记位于有文本之间的标记之前。
返回文本工作正常,但我无法返回src。我在构建一个源自当前迭代循环的xpath时遇到了麻烦。我剩下的就是“无法找到”或者我一遍又一遍地返回第一个菜单图像。
以下是我目前运行的代码(请注意,我无法透露网站的网址):
menu_button = browser.find_element_by_xpath(
'//span[@class="ThemeOfficeMainFolderText"]/preceding-sibling::span/img').get_attribute('src')
我不确定语法是否完全正确/我是否可以使用当前迭代的元素作为我的find_element函数的“根”(menu_part.find_element_by_xpath) 此外,无法使用属性进一步指定标记,因为所有菜单项都具有相同的属性。 最后,以下代码返回菜单中的第一个图像。
<td class="ThemeOfficeMainItem" onmouseover="ItemMouseOverOpenSub ()">
<span class="ThemeOfficeMainFolderLeft">
<img src="img1.png"></span>
<span class="ThemeOfficeMainFolderText">TEXT</span>
<span class="ThemeOfficeMainFolderRight"> </span>
</td>
<td class="ThemeOfficeMainItem" onmouseover="ItemMouseOverOpenSub ()">
<span class="ThemeOfficeMainFolderLeft">
<img src="img2.png"></span>
<span class="ThemeOfficeMainFolderText"></span>
<span class="ThemeOfficeMainFolderRight"> </span>
</td>
因此,我相对确信“span [@class ...”之后的代码工作正常,问题是前面的代码。
我希望有一个简单的解决方案,我在编写xpath时犯了一个错误,但我现在完全没有想法......
编辑:
这是我正在处理的基本html结构
{{1}}
答案 0 :(得分:1)
如果您想从先前定义的父元素span
开始搜索menu_part
,那么您应该使用
./span[@class="ThemeOfficeMainFolderText"]/preceding-sibling::span/img
请注意XPath
开头指向当前(menu_part
)元素的点
<强>更新强>
关于代码的逻辑,请尝试以下:
browser = webdriver.Chrome()
browser.get(URL)
menu = browser.find_elements_by_xpath('//td[@onmouseover]')
for menu_part in menu:
text_span = menu_part.find_element_by_xpath('./span[@class="ThemeOfficeMainFolderText"]')
if not text_span.text:
menu_button = menu_part.find_element_by_xpath('./span[@class="ThemeOfficeMainFolderText"]/preceding-sibling::span/img').get_attribute('src')
else:
menu_button = text_span.text
print menu_button