您需要导入以下库。
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
要获取所有元素,请尝试以下代码。 visibility_of_all_elements_located() 并遵循 xpath
allelements=WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.XPATH,"//td[@class='dataTD' and @colspan='2']/following::td[1]")))
for item in allelements:
print(item.text)
或使用以下 css 选择器。
allelements=WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"td.dataTD[colspan='2']+td")))
for item in allelements:
print(item.text)
** 预期输出**:
Year Month Domestic
2003 December 1,424.216
2003Total - 15,232.525
%Chg over 2002 -
Q4 Only 5.13%
2004 January 1,234.820
已编辑
根据您的预期输出。这是更新的代码。
创建一个函数并传递字符串值。
def Get_details(strtext):
Year=[]
Month=[]
Domestic=[]
allelements=WebDriverWait(driver,20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR,"td.dataTD")))
for element in allelements:
if element.text==strtext and element.get_attribute("colspan")=='2':
Year.append(element.find_element_by_xpath("./parent::tr/preceding-sibling::tr[1]/td[1]").text)
Month.append(element.find_element_by_xpath("./parent::tr/preceding-sibling::tr[1]/td[2]").text)
Domestic.append(element.find_element_by_xpath("./parent::tr/preceding-sibling::tr[1]/td[3]").text)
Year.append(element.text)
Month.append("-")
Domestic.append(element.find_element_by_xpath("./following::td[1]").text)
if element.find_element_by_xpath("./parent::tr/following-sibling::tr[1]/td[1]").get_attribute("colspan")=='2':
Year.append(element.find_element_by_xpath("./parent::tr/following-sibling::tr[1]/td[1]").text)
Month.append("-")
Domestic.append(element.find_element_by_xpath("./parent::tr/following-sibling::tr[1]/td[2]").text)
Year.append(element.find_element_by_xpath("./parent::tr/following-sibling::tr[2]/td[1]").text)
Month.append(element.find_element_by_xpath("./parent::tr/following-sibling::tr[2]/td[2]").text)
Domestic.append(element.find_element_by_xpath("./parent::tr/following-sibling::tr[2]/td[3]").text)
print(Year)
print(Month)
print(Domestic)
如果你用2003 Total调用函数
Get_details("2003 Total")
输出:
['2003', '2003 Total', '%Chg over 2002\nQ4 Only', '2004']
['December', '-', '-', 'January']
['1,424.216', '15,232.525', '5.13%', '1,234.820']
如果你用2004 Total调用函数
Get_details("2004 Total")
输出:
['2004', '2004 Total', '%Chg over 2003', '2005']
['December', '-', '-', 'January']
['1,526.984', '16,452.807', '8.01%', '1,280.516']