使用Selenium Python获取动态表格数据时遇TypeError问题求助
Hey there, let's break down why you're hitting this error and fix it quickly.
The Root Cause
That TypeError is happening because you're trying to concatenate integers (row and col from your range() loops) directly with strings in your XPath. Python doesn't allow mixing int and str types in string concatenation—you need to convert those integers to strings first.
Looking at your problematic line:
values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr["+row+"]/td["+col+"]").text
row and col are integers from range(rows) and range(columns), so when you try to add them to the XPath string, Python throws that error.
Bonus Issue: Table Indexing
Also, heads up—HTML table rows/columns start at index 1, but your range() loops start at 0. That means your first iteration will look for tr[0] which doesn't exist in the DOM, so even after fixing the type error, you'd get a NoSuchElementException later.
The Fixes
Here are two clean ways to fix the type error, plus adjusting the loop indices:
1. Use f-strings (Recommended, Python 3.6+)
F-strings make string formatting way cleaner and avoid concatenation issues entirely:
for row in range(1, rows + 1): # Start at 1 instead of 0 for col in range(1, columns + 1): values = self.driver.find_element_by_xpath(f".//*[@id='table01']/tbody/tr[{row}]/td[{col}]").text print(f"Dynamic web table index {row}, {col} value is {values}")
2. Convert Integers to Strings Explicitly
If you're using an older Python version, convert row and col to strings with str():
for row in range(1, rows + 1): for col in range(1, columns + 1): values = self.driver.find_element_by_xpath(".//*[@id='table01']/tbody/tr[" + str(row) + "]/td[" + str(col) + "]").text print("Dynamic web table index {}, {} value is {}".format(row, col, values))
Full Updated Test Method
Here's what your test_get_table_data method should look like after fixes:
def test_get_table_data(self): time.sleep(10) columns = len(self.driver.find_elements_by_xpath(".//*[@id='table01']/tbody/tr[1]/td")) rows = len(self.driver.find_elements_by_xpath(".//*[@id='table01']/tbody/tr")) print("rows - ", rows) # rows - 3 print("columns - ", columns) # columns - 4 # Iterate from 1 to rows/columns inclusive for row in range(1, rows + 1): for col in range(1, columns + 1): values = self.driver.find_element_by_xpath(f".//*[@id='table01']/tbody/tr[{row}]/td[{col}]").text print(f"Dynamic web table index {row}, {col} value is {values}")
This should resolve both the type error and the potential missing element issue.
内容的提问来源于stack exchange,提问作者surya kumar

