AttributeError:“列表”对象在 Selenium Python 中没有属性“文本”

Imr*_*ran 1 selenium webdriver list python-3.x selenium-webdriver

这是代码......

from selenium import webdriver

url = 'https://infobypokharelk.blogspot.com/'
driver = webdriver.Firefox()
driver.get(url)

row_count = len(driver.find_elements_by_xpath("//*[@id='post-body-6767393087210111064']/div[1]/table/tbody/tr"))
col_count = len(driver.find_elements_by_xpath("//*[@id='post-body-6767393087210111064']/div[1]/table/tbody/tr[1]/td"))

print("Number if Rows:",row_count)
print("Number of Columns",col_count)

first_part = "//*[@id='post-body-6767393087210111064']/div[1]/table/tbody/tr["
secound_part = "]/td["
third_part = "]"

for n in range(1,row_count+1):
    for m in range(1,col_count+1):
        final_path = first_part + str(n) + secound_part + str(m) + third_part
        table_data = driver.find_elements_by_xpath(final_path).text
        print(table_data,end = " ")
    print()
Run Code Online (Sandbox Code Playgroud)

输出是..

 File "tut_td.py", line 15, in <module>
    table_data = driver.find_elements_by_xpath(final_path).text
 AttributeError: 'list' object has no attribute 'text'
Run Code Online (Sandbox Code Playgroud)

Ant*_*ite 5

find_elements_by_xpath返回一个元素列表,而不仅仅是一个元素,因此您需要使用循环迭代它们,或者如果您认为第一个元素是唯一的,则只获取第一个元素:

table_data = driver.find_elements_by_xpath(final_path)[0].text
Run Code Online (Sandbox Code Playgroud)