我是 selenium 和 python 的初学者,我试图理解条件语句的逻辑,但它没有考虑第二个条件:
我想做什么:
PS:我把“?”,因为我不确定是不是
我的代码:
users = []
elems = browser.find_elements_by_xpath("//body//div[@class='PZuss']//a[@class='FPmhX notranslate _0imsa ']")
url = "https://www.instagram.com/"
# Generate a list where to put the followers name
for i in range(100):
val = elems[i].get_attribute('innerHTML')
users.append(url+val)
print(users)
for follower in users:
#Iterate into the list
browser.get(follower)
sleep(2)
followButton = browser.find_element_by_css_selector('button')
print(follower_count)
print(following_count)
if int(follower_count) == 0:
follower_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/span/span').text.replace(",",""))
following_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[3]/span/span').text.replace(",",""))
continue #don't know if i need this word ?
if browser.find_elements_by_xpath("//img[contains(@src,'YW5vbnltb3VzX3Byb2ZpbGVfcGlj')]"):
print("profil haven't profil pic")
continue
else:
print("eligible")
followButton.click()
答案 0 :(得分:0)
我对您要实现的目标的理解是这样的。
if int(follower_count) == 0:
follower_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[2]/span/span').text.replace(",",""))
following_count = int(browser.find_element_by_xpath('/html/body/div[1]/section/main/div/header/section/ul/li[3]/span/span').text.replace(",",""))
if browser.find_elements_by_xpath("//img[contains(@src,'YW5vbnltb3VzX3Byb2ZpbGVfcGlj')]"):
print("profil haven't profil pic")
else:
print("eligible")
followButton.click()
您不需要 continue
代码即可工作
第二个 if 语句在第一个 if 语句中,else
是第二个 if 语句的一部分。缩进的代码块在第一个 if 语句中,并且只有在 follower_count 等于 0 时才运行,否则它将跳过 if 语句并转到 for 循环中的下一个值。
答案 1 :(得分:0)
您应该在这里使用逻辑运算符。假设您在三个专用方法中有条件检查和验证逻辑:
def check_condition_one(*args):
pass # You evaluate your conditions here
def check_condition_two(*args):
pass # You evaluate your conditions here
def validate(*args):
pass # you implement your validation logic here
然后你这样做:
for user in users:
if check_condition_one(user) and check_condition_two(user):
validate(user)
因此,当两个条件都评估为 True
时,您验证用户。否则什么都不会发生。
P.S. - continue
只是跳过其余代码,直到当前循环迭代结束,如果有的话,继续进行下一个。