如何迭代列表?

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

当我运行代码时,它会转到 Twitter 并从文本列表中发布一条推文,但之后它使用列表中相同的第一个推文 (test1) 并用它创建一条新推文

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time 
from selenium.webdriver.common.by import By
username_xpath = '/html/body/div/div/div/div[1]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/div/div/div[4]/label/div/div[2]/div/input'
button_xpath = '/html/body/div/div/div/div[1]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div/div/div/button[2]/div'
password_xpath = '//*[@id="layers"]/div/div/div/div/div/div/div[2]/div[2]/div/div/div[2]/div[2]/div[1]/div/div/div[3]/div/label/div/div[2]/div[1]/input'

driver = webdriver.Chrome()
driver.get("https://x.com/i/flow/login")

element = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, username_xpath)))
driver.find_element(By.XPATH,username_xpath).send_keys("username")   

element = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, button_xpath)))
driver.find_element(By.XPATH,button_xpath).click()

element = WebDriverWait(driver, 30).until(EC.presence_of_element_located((By.XPATH, password_xpath)))
driver.find_element(By.XPATH,password_xpath).send_keys("password")

element = WebDriverWait(driver,5).until(EC.presence_of_element_located((By.CSS_SELECTOR, '[data-testid="LoginForm_Login_Button"]')))
driver.find_element(By.CSS_SELECTOR, '[data-testid="LoginForm_Login_Button"]').click()
time.sleep(3)

Text = [
    "test1",
    "test2"
]


with open(r'C:\Users\user\Desktop\pyhton\test\account.txt', 'r') as file:
    for at_in_txt in file:
        driver.get('https://x.com/compose/post')
        time.sleep(4)
        tweet = driver.find_element(By.XPATH,'''(//div[@class='public-DraftStyleDefault-block public-DraftStyleDefault-ltr'])[1]''')

        for item in Text:
            for char in item:
                tweet.send_keys(char)
                time.sleep(0.015)
            break
        tweet.send_keys(' ')
        for item in at_in_txt:
            tweet.send_keys(item)
            time.sleep(0.015)

        time.sleep(10)

我希望它用 test1 制作一条推文,然后用 test2 制作另一条推文作为推文,就像 for 循环一样,迭代循环中的所有项目

selenium-webdriver web-scraping twitter
1个回答
0
投票

二手

tweet_content = random.choice(Text)
for char in tweet_content:
    tweet.send_keys(char)
    time.sleep(0.015) 
© www.soinside.com 2019 - 2024. All rights reserved.