Selenium随机点击帖子链接问题:现有代码无法实现随机点击功能
Fixing Random Post Clicks with Selenium
Hey there! The issue with your current code is that it's iterating through post links in strict order instead of picking them randomly. Let's adjust it to add that random behavior, plus fix a common pitfall with stale elements when navigating back to the list page.
What's off with the original code?
- You’re collecting all link texts first and looping through them sequentially—no randomness involved here.
- When you navigate back to the list page with
driver.back(), the original link elements you stored earlier might become "stale" (since the page reloads subtly), which could trigger errors later on.
Updated Code with Random Clicks
Here's the revised version that picks random posts each time, handles stale elements, and repeats the browsing process as needed:
from time import sleep from selenium import webdriver import random # Add this module for random selection driver = webdriver.Chrome() driver.implicitly_wait(10) driver.get("https://your-full-url-here/test") # Replace with your actual full list page URL # Set how many random posts you want to browse number_of_browses = 10 for _ in range(number_of_browses): # Re-fetch links every time we return to the list page (avoids stale elements) list_of_links = driver.find_elements_by_xpath('//a[@class="re_href"]') # Pick a random link from the current list random_link = random.choice(list_of_links) # Click the random post (use execute_script if regular click fails due to overlays) random_link.click() # driver.execute_script("arguments[0].click();", random_link) # Uncomment if needed # Wait 3 seconds to view the content sleep(3) # Navigate back to the list page driver.back() # Short wait to let the list page load fully sleep(2) driver.quit() # Properly close the browser when done
Key Improvements:
- Added
import randomto enable random selection of links directly from the element list. - Re-fetches
list_of_linksin each loop: This avoids stale element exceptions, as navigating back can reset the page's DOM elements. - Uses
random.choice(list_of_links)to pick a random post—no need to rely on link text (which might have duplicates, like in your HTML example). - Added a
number_of_browsesvariable to control how many random posts you want to browse. - Added
driver.quit()to cleanly close the browser session when finished.
Quick Notes:
- Replace
"https://your-full-url-here/test"with the actual full URL of your list page (your original code uses a relative path, which may not work unless the driver is already on the correct domain). - If
random_link.click()fails (e.g., elements are covered by overlays), uncomment theexecute_scriptline—it’s a more robust click method for tricky UI scenarios.
内容的提问来源于stack exchange,提问作者soria
相关产品推荐
相关产品推荐

