下载地址:https://www.pan38.com/dow/share.php?code=JCnzE 提取密码:6477
这个代码展示了如何使用Selenium模拟人类观看视频的行为,包括随机滚动、暂停/播放和点赞等操作。请注意这仅用于学习自动化测试技术,实际使用时请遵守各平台的使用条款。
import time
import random
import pyautogui
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class VideoAutoPlayer:
def init(self, headless=False):
self.options = Options()
if headless:
self.options.add_argument("--headless")
self.driver = webdriver.Chrome(options=self.options)
self.wait = WebDriverWait(self.driver, 15)
def login(self, username, password):
self.driver.get("https://www.example.com/login")
email_field = self.wait.until(
EC.presence_of_element_located((By.ID, "email"))
)
email_field.send_keys(username)
pass_field = self.driver.find_element(By.ID, "password")
pass_field.send_keys(password)
pass_field.send_keys(Keys.RETURN)
time.sleep(5)
def watch_video(self, video_url, watch_time):
self.driver.get(video_url)
time.sleep(3)
# 模拟人类观看行为
start_time = time.time()
while time.time() - start_time < watch_time:
# 随机滚动
if random.random() > 0.7:
scroll_amount = random.randint(100, 500)
self.driver.execute_script(f"window.scrollBy(0, {scroll_amount})")
# 随机暂停/播放
if random.random() > 0.9:
pyautogui.press("space")
time.sleep(random.uniform(1, 3))
pyautogui.press("space")
# 随机点赞
if random.random() > 0.95:
try:
like_btn = self.driver.find_element(
By.XPATH, "//button[contains(@aria-label,'Like')]"
)
like_btn.click()
except:
pass
time.sleep(random.uniform(5, 15))
def browse_homepage(self, duration):
self.driver.get("https://www.example.com")
start_time = time.time()
while time.time() - start_time < duration:
videos = self.driver.find_elements(
By.CSS_SELECTOR, ".video-item"
)
if videos:
random.choice(videos).click()
time.sleep(random.uniform(30, 120))
self.driver.back()
time.sleep(2)
def close(self):
self.driver.quit()
if name == "main":
bot = VideoAutoPlayer(headless=False)
try:
bot.login("your_username", "yourpassword")
for in range(10):
bot.browse_homepage(600) # 浏览10分钟
bot.watch_video("https://www.example.com/video123", 300) # 观看5分钟
finally:
bot.close()