使用Python Selenium从主XPath下的两个元素类型值获取数据

问题描述 投票:0回答:1

行数和顺序不固定。这是随机的。。所附图片仅显示两种类型的 html 行。

A行是2,3,4,5,7,8,9,10,11,12,13,15,我想提取class =“message-in focusable-list-item的数据.....”(以绿色突出显示)。

B 型行 为 1,6,11,14。我想提取 tableindex = "-1".

enter image description here

我尝试使用以下方法使用给定的 XPath 从 Type A row 获取值。成功了。

msgInOutPath = '//*[@id="main"]/div[3]/div/div[2]/div[3]/div[8]/div/div'
msgInOut = wait.until(EC.presence_of_element_located((By.XPATH, msgInOutPath)))
classValue = msgInOut.get_attribute('class')
print(f'Class: {classValue}')

mainXPath = '//*[@id="main"]/div[3]/div/div[2]/div[3]'

问题是A型和B型序列是随机的。行数也是随机的。

  1. 如何检查主XPath下该行是Type A还是Type B并获取我想要的数据?

提前感谢您提供的所有专业提示!

python html selenium-webdriver
1个回答
0
投票

使用

main_x_path
查找该部分中的所有行。循环遍历每个行元素。在循环内,使用另一个 XPath 表达式来检查 A 类或 B 类行的特定标识符。

for i in range(1, len(driver.find_elements_by_xpath(main_x_path+ "/div")) + 1):
    row_xpath = maix_x_path + f"/div[{i}]"
    row_element = wait.until(EC.presence_of_element_located((By.XPATH, row_xpath)))

    # Check for Type A
    if i in [2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 15]:  # Adjust based on your list
        msgInOutPath = row_xpath + "/div/div"  # Assuming message element is nested within another div
        msgInOut = wait.until(EC.presence_of_element_located((By.XPATH, msgInOutPath)))
        classValue = msgInOut.get_attribute('class')
        print(f'Type A, Class: {classValue}')
    
    # Check for Type B
    elif i in [1, 6, 11, 14]:  # Adjust based on your list
        table_index_element = row_element.find_element_by_xpath(".//div[@tableindex='-1']") 
        table_index_value = table_index_element.text  .get_attribute('tableindex') if needed
        print(f'Type B, tableindex: {table_index_value}')

    # Handle cases where the row doesn't belong to either type
    else:
        print(f'Unidentified row type at position {i}')
© www.soinside.com 2019 - 2024. All rights reserved.