简体   繁体   English

循环遍历行以使用selenium和python获取列数据

[英]Loop through rows to get column data using selenium and python

I'm trying to use Python 3.6 and Selenium to grab data form a table. 我正在尝试使用Python 3.6和Selenium从表中获取数据。 One of the tables I'm trying to grab from has multiple rows. 我试图从中获取的一个表有多行。 So, I want to get column 9 from each row. 所以,我想从每一行得到第9列。

I searched around on this site and found some code that I was able to adapt to almost work. 我在这个网站上搜索过,发现了一些我能够适应几乎工作的代码。

table_id = driver.find_element(By.ID, 'ctl00_mid_rptItems_ctl00_gvItems')
rows = table_id.find_elements(By.TAG_NAME, "tr")
for row in rows:
    cols = row.find_elements(By.TAG_NAME, "td")  
    for col in cols:
        print (cols[8].text)

It spits out the correct data from the column I want, but the problem I'm having is that it loops through each row 16 times, which is the number of columns in the table, and prints each data point 16 times. 它从我想要的列中吐出正确的数据,但我遇到的问题是它遍历每一行16次,这是表中的列数,并打印每个数据点16次。

I tried to adapt the code above to just spit out each column 1 time by removing the "for col" loop 我试图通过删除“for col”循环来调整上面的代码,只是吐出每列一次

table_id = driver.find_element(By.ID, 'ctl00_mid_rptItems_ctl00_gvItems')
rows = table_id.find_elements(By.TAG_NAME, "tr")
for row in rows:
    cols = row.find_elements(By.TAG_NAME, "td")
    print (cols[8].text)

But, this gives the the error "Traceback (most recent call last): File "C:\\Users\\Documents\\PleaseTest_R1.py", line 91, in 但是,这会给出错误“Traceback(最近一次调用最后一次):文件”C:\\ Users \\ Documents \\ PleaseTest_R1.py“,第91行,
print (cols[8].text) IndexError: list index out of range print(cols [8] .text)IndexError:列表索引超出范围

Any ideas on how I can get this loop to work? 关于如何让这个循环工作的任何想法?
Thanks so much for the help! 非常感谢你的帮助! :-) :-)

I can suggest you to use Javascript, Execute this JavaScript via your python program, it will work. 我可以建议你使用Javascript,通过你的python程序执行这个JavaScript,它会工作。

Systax to take content from the cell, Systax从细胞中取出内容,

document.getElementId("tableid").rows[3].cells[4].innerHTML

And you can get row count by 你可以通过计算行数

document.getElementId("tableid").rows.length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM