Selenium、Python - 使用 For 循环查找列中的值,但导致重复第一个值
以上是我尝试仅提取名称列的实践网站。然而,从我的 For 循环中,我重复计算了 Alan 这个名字五次(见下面的图片)。不幸的是,我的 For 循环也将标题行计为第 0 行。
代码:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#Scenario a HTML table is provided
#Feature: HTML table
def test_table():
URL = 'https://testpages.herokuapp.com/styled/tag/table.html'
#Given website loaded a table <--The Set Up
b=webdriver.Chrome()
b.get(URL)
wait=WebDriverWait(b,20)
#When user arrives at the website and sees a table <-- IGNORE, when print text, all values are correct.
table=b.find_element(By.ID,'mytable')
#Then the table shows a column of names <-- The issue
rows=b.find_elements(By.TAG_NAME,'tr')
for i, col in enumerate(rows):
col=b.find_element(By.TAG_NAME,'td').text
print(f'Row: {i}, Name: {row}')
b.quit()
test_table()
结果:
我曾想过使用预期条件,但该表是静态的。这导致我决定没有必要使用预期条件。另外,我曾认为标签名称使用不正确,但事实并非如此。任何助手都会受到赞赏。
Above is the practice website I am attempting to extract only the name column. However, from my For-loop, I am repeatedly accounting the name Alan five times (see img below). Unfortunately, my For-loop counted the header row too as row 0.
Code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
#Scenario a HTML table is provided
#Feature: HTML table
def test_table():
URL = 'https://testpages.herokuapp.com/styled/tag/table.html'
#Given website loaded a table <--The Set Up
b=webdriver.Chrome()
b.get(URL)
wait=WebDriverWait(b,20)
#When user arrives at the website and sees a table <-- IGNORE, when print text, all values are correct.
table=b.find_element(By.ID,'mytable')
#Then the table shows a column of names <-- The issue
rows=b.find_elements(By.TAG_NAME,'tr')
for i, col in enumerate(rows):
col=b.find_element(By.TAG_NAME,'td').text
print(f'Row: {i}, Name: {row}')
b.quit()
test_table()
Result:
I had thought of using the expected condition, but the table is static. Which led to me deciding that the use of expected condition wasn't necessary. Also, I had considered that the tag name wasn't used correctly, but this wasn't the case. Any assistant is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在遍历整个页面,而不仅仅是行。由于您在循环中搜索单个元素,因此它返回页面的第一个
td
元素。应该是You are traversing the whole page instead of just the rows. And since you are searching for single element in the loop, it returns the first
td
element of the page. It should be