我正在编写一个脚本,用于查找特定群组中 Instagram 上关注者少于 5001 名的用户。该代码崩溃了,对于它被调用的前两个实例不起作用,但对于前两个实例之后的所有实例都工作得很好。我检查了html代码,所有用户的html代码都是相同的。我真的不知道为什么它会崩溃并且在它被调用的前两个实例中不起作用。
这是html代码:
<span class="g47SY ">130</span>
<span class="g47SY " title="1,198">1,198</span>
这是原始代码(删除了 try/except 函数,使其能够在调用的前两个实例之后工作):
#Finds User Statistics including following/followers
user_stats = driver.find_elements_by_xpath("//span[contains(@class, 'g47SY ')]")
stat_list = []
for user in user_stats:
#Gets the string integer values and saves to a list
stats = user.get_attribute('innerHTML')
stat_list.append(stats)
#Decides if user has less than 5001 followers
if int(stat_list[1]) <= 5001:
print("Has less than 5001 followers")
删除 try/except 语句后,我收到的错误消息是:
Traceback (most recent call last):
File "C:\Users\\Desktop\FINAL - Copy.py", line 91, in follow
if int(stat_list[1]) <= 5001:
ValueError: invalid literal for int() with base 10: '1,198'
我通过将 stat_list 转换为 float 或 int 尝试了以下两种解决方案,反之亦然,以下是这些解决方案的错误消息以及代码:
if float(int(stat_list[1])) <= 5001:
ValueError: invalid literal for int() with base 10: '1,198'
if int(float(stat_list[1])) <= 5001:
ValueError: could not convert string to float: '1,198'
最佳答案
发生这种情况是因为 ,
正在从关注者号码中获取。因此,您需要首先将其从计数中删除,然后将断言放在数字上。
您可以使用以下方法删除它:
# Put the value which you want to replace in the below code
value.replace(",", "")
关于Python/Selenium 在比较转换为整数值的字符串时有非常奇怪的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59514050/