我有这小段代码,希望在某些值之间随机进行
for i in range(1, ad.photo_counter()):
photo_field = self.browser.find_elements_by_xpath('//input[@type="file"]')[i]
photo_field.send_keys(ad.photos[i])
ad.photo_counter()
获取存储在文件夹中的照片总数。可以说这是3。然后,我希望send_key(ad.photos[i])
是一个随机数,而不是一个从1到10的整数。有想法吗?
答案 0 :(得分:3)
您可以使用random.randint(low, high)
import random
index = random.randint(0, NUM_PHOTOS) # assuming you have the number of photos in NUM_PHOTOS
或者您可以使用random.choice(list)
import random
pickedPhoto = random.choice(ad.photos)
答案 1 :(得分:1)
将您的range(1, ad.photo_counter())
转换为列表,然后使用random.shuffle:
import random
my_values = list(range(1, 10))
random.shuffle(my_values)
print(my_values)
答案 2 :(得分:1)
为此,您需要import random
并致电random.randint(inclusive,exclusive)
。
import random
for i in range(1, ad.photo_counter()):
photo_field = self.browser.find_elements_by_xpath('//input[@type="file"]')[i]
photo_field.send_keys(ad.photos[random.randint(0,ad.photo_counter())])
您可以在this link中查看如何在python中执行随机数生成
答案 3 :(得分:1)
您可以执行此操作的另一种方法是使用random.sample
(https://docs.python.org/3/library/random.html#random.sample)。此函数通过从值列表中随机采样来生成k个值列表。因此,以代码形式可以执行以下操作:
import random
for i in random.sample(range(1, ad.photo_counter()), k = ad.photo_counter() - 1):
photo_field = self.browser.find_elements_by_xpath('//input[@type="file"]')[i]
photo_field.send_keys(ad.photos[i])
这将创建从1到ad.photo_counter() - 1
的值的随机排列。 k等于ad.photo_counter() - 1
,因为您从索引1开始,否则将省略-1。然后,可以使用for循环遍历此随机排列,以生成随机的索引序列,以选择没有重复的照片。
希望这会有所帮助!