如何循环动作?

2024-04-28 19:44:31 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我目前正在开发一个机器人,机器人是100%工作,但我不知道如何使它循环。你知道吗

import time
from random import randint
from time import sleep
import csv
import requests
from selenium import webdriver
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as bs4

#Login information


#chromedriver
driver = webdriver.Chrome(executable_path=r'C:/Webdriver/chromedriver.exe')
#Open hellcase
driver.get("http://www.hellcase.com/en")
time.sleep(2)
driver.get("https://hellcase.com/login")
time.sleep(2)
elem = driver.find_element_by_id("steamAccountName")
elem.send_keys(user)
time.sleep(1)
elem = driver.find_element_by_id("steamPassword")
elem.send_keys(password)

driver.find_element_by_id("imageLogin").click()

time.sleep(30)
driver.get("https://hellcase.com/en/profile/xxxxxx")

time.sleep(2)
driver.find_element_by_xpath('//*[@id="my- 
items"]/div[2]/div[1]/a[1]').click()
time.sleep(5)
driver.find_element_by_xpath('//*[@id="confirm"]/div[3]/a').click()
time.sleep(2)
driver.find_element_by_xpath('//*[@id="my- 
items"]/div[2]/div[1]/a[1]').click()
sleep(randint(1,7))

这是我想反复重复的部分

driver.find_element_by_xpath('//*[@id="my- 
items"]/div[2]/div[1]/a[1]').click()
time.sleep(5)
driver.find_element_by_xpath('//*[@id="confirm"]/div[3]/a').click()
time.sleep(2)
driver.find_element_by_xpath('//*[@id="my- 
items"]/div[2]/div[1]/a[1]').click()
sleep(randint(1,7)) 

有人能帮我怎么做吗?你知道吗


Tags: fromimportdividbytimemydriver
1条回答
网友
1楼 · 发布于 2024-04-28 19:44:31

要在Python中一遍又一遍地重复操作,可以使用while循环。例如,要无限期地重复代码块,可以使用:

while True:
    driver.find_element_by_xpath('//*[@id="my- 
    items"]/div[2]/div[1]/a[1]').click()
    time.sleep(5)
    driver.find_element_by_xpath('//*[@id="confirm"]/div[3]/a').click()
    time.sleep(2)
    driver.find_element_by_xpath('//*[@id="my- 
    items"]/div[2]/div[1]/a[1]').click()
    sleep(randint(1,7)) 

while关键字需要一个表达式(这里是True)来确定是继续还是退出循环。你可以把任何东西放在while后面,这将使计算结果变得真实或虚假

a = 0    
while a < 10:
    a = a + 1
    print(a)

通过给True作为表达式,它的值总是True,循环将无限期地继续。您也可以使用while 1=1:。你知道吗

相关问题 更多 >