You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Selenium爬虫:如何将str(len(rows))转换为整数?

问题:Python Selenium获取表格行数时的类型错误问题

我正在用Python的Selenium做网页爬虫项目,刚接触Python,在把网页表格的行数输出为整数时遇到了问题。网上找的方法是:

table = driver.find_element(by = By.ID, value = 'webtable')
tableRows = table.find_elements(by = By.TAG_NAME, value = 'tr')
print('rows: ' + str(len(tableRows)))

运行后输出的是字符串,没法用到需要整数的场景里。比如写:

print('rows: ' + str(len(tableRows)) - 1)

会报错:

TypeError: unsupported operand type(s) for -: 'str' and 'int'

我试过把str换成int,也试过用int包裹整个内容,但还是报错,该怎么解决?


解决方案

核心问题是运算顺序和类型转换时机错误:你当前代码先把行数转成字符串并和文本拼接,再试图用拼接后的字符串减1——字符串和整数无法直接做减法运算,所以报错。

正确的处理逻辑是:先完成整数运算,再将结果转为字符串进行拼接。

方法1:分步处理(清晰直观)

table = driver.find_element(by = By.ID, value = 'webtable')
tableRows = table.find_elements(by = By.TAG_NAME, value = 'tr')
# 先获取整数类型的行数
row_count = len(tableRows)
# 直接输出行数
print('rows: ' + str(row_count))
# 如果需要行数减1的结果,先做整数运算再转字符串
print('rows minus 1: ' + str(row_count - 1))

方法2:使用f-string(简洁高效,Python 3.6+支持)

f-string会自动帮你处理类型转换,无需手动调用str(),代码更简洁不易出错:

table = driver.find_element(by = By.ID, value = 'webtable')
tableRows = table.find_elements(by = By.TAG_NAME, value = 'tr')
print(f'rows: {len(tableRows)}')
print(f'rows minus 1: {len(tableRows) - 1}')

为什么之前的尝试报错?

比如你写print('rows: ' + int(len(tableRows))),这是把已经是整数的len(tableRows)再次转成整数(无意义),然后试图将字符串和整数直接用+拼接——Python不允许字符串和整数直接拼接,因此报错。必须确保拼接的两边都是字符串类型,或者用f-string自动处理转换。


内容的提问来源于stack exchange,提问作者Mohamed Salem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 19:27:22