使用Selenium和Python保存表格

3 投票
1 回答
11458 浏览
提问于 2025-04-17 06:23

我正在尝试用Python和Selenium来保存一个表格的内容。我的脚本如下:

import sys
import selenium
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://testsite.com")

value = selenium.getTable("table_id_10")

print value

driver.close()

这个脚本会打开我感兴趣的网页,然后应该保存我想要的表格内容。我看到在这个问题中有一种语法,使用了browser.get_table(),但那个程序的开头是browser=Selenium(...),我不太明白这是什么意思。我不确定我应该使用什么语法,因为selenium.getTable("table_id_10")是错误的。


补充:

我附上了我正在使用的表格的HTML片段:

<table class="datatable" cellspacing="0" rules="all" border="1" id="table_id_10" style="width:70%;border-collapse:collapse;">
    <caption>
        <span class="captioninformation right"><a href="Services.aspx" class="functionlink">Return to Services</a></span>Data
    </caption><tr>
        <th scope="col">Read Date</th><th class="numericdataheader" scope="col">Days</th><th class="numericdataheader" scope="col">Values</th>

    </tr><tr>
        <td>10/15/2011</td><td class="numericdata">92</td><td class="numericdata">37</td>
    </tr><tr class="alternaterows">
        <td>7/15/2011</td><td class="numericdata">91</td><td class="numericdata">27</td>
    </tr><tr>
        <td>4/15/2011</td><td class="numericdata">90</td><td class="numericdata">25</td>    
</table>

1 个回答

17

旧版的Selenium RC API里面有一个叫做get_table的方法:

In [14]: sel=selenium.selenium("localhost",4444,"*firefox", "http://www.google.com/webhp")
In [19]: sel.get_table?
Type:       instancemethod
Base Class: <type 'instancemethod'>
String Form:    <bound method selenium.get_table of <selenium.selenium.selenium object at 0xb728304c>>
Namespace:  Interactive
File:       /usr/local/lib/python2.7/dist-packages/selenium/selenium.py
Definition: sel.get_table(self, tableCellAddress)
Docstring:
    Gets the text from a cell of a table. The cellAddress syntax
    tableLocator.row.column, where row and column start at 0.

    'tableCellAddress' is a cell address, e.g. "foo.1.4"

但是你现在使用的是更新的Webdriver(也就是Selenium 2)API,所以那个代码不适用了。


你可以试试下面这样的代码:

import selenium.webdriver as webdriver
import contextlib

@contextlib.contextmanager
def quitting(thing):
    yield thing
    thing.close()
    thing.quit()

with quitting(webdriver.Firefox()) as driver:
    driver.get(url)
    data = []
    for tr in driver.find_elements_by_xpath('//table[@id="table_id_10"]//tr'):
        tds = tr.find_elements_by_tag_name('td')
        if tds: 
            data.append([td.text for td in tds])
print(data)
# [[u'10/15/2011', u'92', u'37'], [u'7/15/2011', u'91', u'27'], [u'4/15/2011', u'90', u'25']]

撰写回答