如何制作Selenium元素列表?

时间:2016-01-05 23:25:38

标签: python list loops selenium

我在Python中使用selenium webdriver,我需要在循环中使用它: 我可以这样做:

a=browser.find_element_by_xpath("//tbody[@id='mrc_main_table']/tr/td[1]")
b=browser.find_element_by_xpath("//tbody[@id='mrc_main_table']/tr/td[2]")
c=browser.find_element_by_xpath("//tbody[@id='mrc_main_table']/tr/td[3]")
d=browser.find_element_by_xpath("//tbody[@id='mrc_main_table']/tr/td[n]")

1)但我想要这样的事情:

var==browser.find_element_by_xpath("//tbody[@id='mrc_main_table']/tr/td[ALL_value]")

2)我需要像这样输出数组:

 output=[ANDERSON,ISAIAH,DWIGHT,....]

以下是代码:

    import xlwt
    from tempfile import TemporaryFile
    from selenium import webdriver
    browser =webdriver.Firefox()
    browser.get( "https://report.boonecountymo.org/mrcjava/servlet/SH01_MP.I00290s" )
    element=browser.find_element_by_xpath("//tbody[@id='mrc_main_table']/tr/td[1]" )#I want this as list
    output=element.text #I want this as list
    print output

    book = xlwt.Workbook()
    sheet1 = book.add_sheet('sheet1')
    output=[ANDERSON,ISAIAH,DWIGHT,....]
    output= [a,b,c]
    for row, array in enumerate(output):
          for col, value in enumerate(array):
             sheet1.write(row, col, value)
    name = "this.xls"
    book.save(name)
    book.save(TemporaryFile())  

任何人都可以帮助我吗?  谢谢

1 个答案:

答案 0 :(得分:0)

list comprehension中使用find_elements_by_xpath(),并且不指定单元格索引:

[td.text for td in browser.find_elements_by_xpath("//tbody[@id='mrc_main_table']/tr/td")]

如果你想拥有每行单元格值列表,你需要生成一个列表列表:

[[td.text for td in row.find_elements_by_tag_name("td")]
 for row in browser.find_elements_by_xpath("//tbody[@id='mrc_main_table']/tr")]

演示:

>>> from selenium import webdriver
>>> from pprint import pprint
>>>
>>> browser = webdriver.Firefox()
>>> browser.get("https://report.boonecountymo.org/mrcjava/servlet/SH01_MP.I00290s")
>>> data = [[td.text for td in row.find_elements_by_tag_name("td")] for row in browser.find_elements_by_xpath("//tbody[@id='mrc_main_table']/tr")]
>>> pprint(data)
[['ACTON', 'CLINTON', 'WAYNE', 'M', 'W', '35', 'STURGEON', 'MO'],
 ['ALLEN', 'SHAUN', 'PHILLIP', 'M', 'W', '28', 'COLUMBIA', 'MO'],
 ['ANDERSON', 'ISAIAH', 'DWIGHT', 'M', 'B', '19', 'COLUMBIA', 'MO'],
 ...
 ['DONATI', 'ROBERT', 'KEITH', 'M', 'W', '52', 'COLUMBIA', 'MO'],
 ['DONIGIAN', 'CHARLES', 'ROSS', 'M', 'W', '20', 'COLUMBIA', 'MO']]