from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.chrome.options import Options
option = Options()
#option.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=option)
driver.get('https://www.outbreak.my/')
time.sleep(10)
confirmed = driver.find_element_by_id('cases-my-confirmed').text
active = driver.find_element_by_id('cases-my-active').text
death = driver.find_element_by_id('cases-my-death').text
cofirmed_changes = driver.find_element_by_id(
'cases-my-confirmed-changes').text
death_changes = driver.find_element_by_id('cases-my-death-changes').text
前面的代码一切正常,问题出现在“用for循环上面”:
states = driver.find_elements_by_xpath(
'//div[@class="card-body o-auto"]//tr')
for s in states:
print(s.find_element_by_css_selector('td.text-value').text)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"css selector","selector":"td.text-value"}
(Session info: chrome=81.0.4044.138)
但是,如果不用for循环,直接states[0],states[1],states[2],states[3],states[4]... ... 便可以取element,无论是by_css_selector/xpath/class_name
states[3].find_element_by_css_selector('td.text-value').text