我试图获得某个产品的评论,但它返回了一个错误。
我的代码:
import selenium
from selenium import webdriver
chrome_path = r"C:UsersAVAppDataLocalProgramsPythonPython39Scriptschromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get("https://oldnavy.gapcanada.ca/browse/product.do?pid=647076053&cid=1180630&pcid=26190&vid=1&nav=meganav%3AWomen%3ADeals%3ASale&grid=pds_0_1034_1#pdp-page-content")
driver.execute_script("window.scrollTo(0, 1000)")
import time
from time import sleep
sleep(5)
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.promoDrawer__handlebar__icon"))).click()
review = driver.find_elements_by_class_name("pr-rd-description-text")
for post in review:
print(post.text)
driver.find_element_by_xpath('//*[@id="pr-review-display"]/footer/div/div/a').click()
review2 = driver.find_elements_by_class_name("pr-rd-description-text")
for post in review2:
print(post.text)
返回:selenium.com.mon.exceptions.ElementNotInteractiableException:消息:元素不可交互
你能告诉我该怎么办吗?
这个按钮真的很难点击。
我想这可以通过添加更多的等待并使用ActionChains
类方法来实现。
我可以用Javascript代码点击它,没有任何问题。它的作用:
1滚动到下一个按钮
2点击它。
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
driver = webdriver.Chrome(executable_path='/snap/bin/chromium.chromedriver')
driver.get(
"https://oldnavy.gapcanada.ca/browse/product.do?pid=647076053&cid=1180630&pcid=26190&vid=1&nav=meganav%3AWomen%3ADeals%3ASale&grid=pds_0_1034_1#pdp-page-content")
driver.execute_script("window.scrollTo(0, 1000)")
wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.promoDrawer__handlebar__icon"))).click()
wait.until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, ".pr-rd-description-text")))
review = driver.find_elements_by_css_selector(".pr-rd-description-text")
for post in review:
print(post.text)
# wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".pr-rd-pagination-btn"))).click()
element = driver.find_element_by_css_selector(".pr-rd-pagination-btn")
# actions = ActionChains(driver)
# actions.move_to_element(element).click().perform()
driver.execute_script("arguments[0].scrollIntoView();", element) # Scrolls to the button
driver.execute_script("arguments[0].click();", element) # Clicks it
print("clicked next")
我还重新排列了您的代码,将导入移到文件的开头,去掉了不可预测的time.sleep()
,并使用了更可靠的css定位器。但是,您的定位器也应该工作。
我把我尝试过的选项都删掉了。
那个元素很奇怪。即使当我滚动到视图中,使用操作来点击它,或者执行javascript来点击它时,它也不起作用。我的建议是从元素中获取href
属性并转到该URL,使用以下内容:
driver.get(driver.find_element_by_xpath('//*[@id="pr-review-display"]/footer/div/div/a').get_attribute('href'))