假如需要读取以下 li的内容:
<ul id="myId">
<li data-value="item-1">Something here</li>
<li data-value="item-2">And here</li>
<li data-value="item-3">Even more here</li>
</ul>
主要是用find_elements的方法找出所有<li>,代码如下:
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
html_list = driver.find_element_by_id("myId")
items = html_list.find_elements_by_tag_name("li")
for item in items:
text = item.text
print text
print(item.get_attribute("data-value"))
也可以更简单的直接一句代码读li出来:
# Get text from all elements
text_contents = [el.text for el in driver.find_elements_by_xpath("//ul[@id='myId']/li")]
# Print contents
for text in text_contents:
print(text)
print(item.get_attribute("data-value"))