使用Selenium遍历Instagram页面时遇WebElement无w3c属性错误求助
Let's break down what's causing this error and how to fix it quickly.
What's Going Wrong?
The root of your AttributeError is a simple misstep in initializing ActionChains. The ActionChains class requires a WebDriver instance (your driver variable) as its argument, not a WebElement. When you pass browser = driver.find_element_by_class_name('_si7dy') into ActionChains(browser), you're giving it a single page element instead of the browser driver itself—and WebElements don't have the w3c attribute that ActionChains checks during setup.
Step-by-Step Fix
1. Correct ActionChains Initialization
Change the line where you create the ActionChains object to use driver instead of the WebElement. If you want to start tabbing from that specific element, first shift focus to it using move_to_element() or a click before sending Tab keys.
2. Corrected Full Code
Here's your updated function with the fix plus small improvements for better debugging:
from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.keys import Keys from bs4 import BeautifulSoup import time def get_posts(tag, user_count): '''Getting html of page to be scrape for hrefs that will get me the user names''' print("getting page") url = "https://www.instagram.com/explore/tags/" + tag + "/" try: driver = webdriver.Chrome() driver.get(url) print("successfully requested site") except Exception as e: print(f"Unable to reach site: {str(e)}") quit() # Get the target element to start tabbing from target_element = driver.find_element_by_class_name('_si7dy') # Initialize ActionChains with the DRIVER, not the element actions = ActionChains(driver) # Focus on the target element first to start tabbing from the right spot actions.move_to_element(target_element).click().perform() for i in range(user_count): actions.send_keys(Keys.TAB).perform() time.sleep(0.5) soup = BeautifulSoup(driver.page_source, 'lxml') try: posts = soup.find_all("div", class_ = ["_mck9w","_gvoze","_f2mse"]) except Exception as e: print(f"No links found: {str(e)}") driver.close() quit() print("Length of posts: ", len(posts)) print(type(posts)) print("All Done") driver.close() return posts
Simpler Alternative for Tab Traversal
If you don't need the advanced features of ActionChains, you can directly send Tab keys to the driver after focusing on your target element. This works perfectly for basic tabbing:
# After locating the target element target_element.click() for i in range(user_count): driver.send_keys(Keys.TAB) time.sleep(0.5)
Key Takeaways
- Always pass the WebDriver instance (
driver) toActionChains, never a WebElement. - Adding a click or
move_to_elementensures your tabbing starts from the correct position on the page. - Wrapping try/except blocks with
Exception as egives you detailed error messages to debug more easily.
内容的提问来源于stack exchange,提问作者Mwspencer

