我在将列表作为自动功能的字符串执行时遇到麻烦

问题描述 投票:1回答:2

我有一个学校项目,我的程序必须执行此代码才能跟随两个用户:

def followWithUsername(self):
    usernames = ['therock', 'justinbieber']
    self.driver.get('https://instagram.com/' + str(usernames) + '/')
    time.sleep(3)
    followButton = self.driver.find_element_by_css_selector('button')
    if (followButton.text != 'Following'):
        followButton.click()
        time.sleep(3)
    else:
        print("You are already following this user.")

我尝试了各种方法,但这不会将用户名彼此分开并一一执行]

python string arraylist instagram
2个回答
1
投票

使用for循环:

def followWithUsername(self):
    usernames = ['therock', 'justinbieber']
    for name in usernames:
        self.driver.get('https://instagram.com/' + name + '/')
        time.sleep(3)
        followButton = self.driver.find_element_by_css_selector('button')
        if (followButton.text != 'Following'):
            followButton.click()
            time.sleep(3)
        else:
            print("You are already following this user.")

1
投票

您需要遍历列表才能对多个值执行此操作。鉴于这是一个学校项目,所以我很乐意为您提供完整的答案。

最好通过使用for loops来实现,您可以在此处阅读更多有关这些的信息:Python FOR Loops

您将遇到并大量使用for循环,在这里,它们是非常有用的一个例子:

values = [1,2,3,4,5,6,7,8,9,10]

# This translates to "For each item stored in the list 'values' perform the following code"

for item in values: 
    print(item)

1
2
3
4
5
6
7
8
9
10

© www.soinside.com 2019 - 2024. All rights reserved.