gpt4 book ai didi

python - 如何使用python selenium递归地点击一个按钮

转载 作者:太空宇宙 更新时间:2023-11-04 11:12:26 25 4
gpt4 key购买 nike

我想递归地点击一个按钮,使用 python selenium 在目标上加载客户评论。例如,使用此产品:
https://www.target.com/p/vanity-fair-everyday-white-napkins-250ct/-/A-14739020
所以在客户评论页面的底部,有一个按钮可以“再加载 8 个”评论。我想在 selenium 中通过打开产品页面来模拟这一点,滚动到页面底部以确保加载元素,然后在元素的 xpath 上单击(),如下所示:

from time import sleep
import csv
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException

class targetProduct:
'''given a product page, return all of the customer reviews'''
def __init__(self):
#start chrome driver
self.mydriver = webdriver.Chrome('/chromedriver.exe')
#enter a product page URL with reviews
self.productpage = "https://www.target.com/p/vanity-fair-everyday-white-napkins-250ct/-/A-14739020"

def open_page(self):
#open the product page and maximize the window
self.mydriver.get(self.productpage)
self.mydriver.maximize_window()
sleep(5)

def button_click(self):
try:
#scroll to the bottom of the page and sleep to ensure the button loads
self.mydriver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
sleep(3)
#click on the button to load 8 more reviews
self.mydriver.find_element_by_xpath('//*[@id="mainContainer"]/div/div/div[2]/div[5]/div/div[2]/div[3]/button').click()
#sleep to load more reviews, then try clicking again to load addition reviews
sleep(3)
self.button_click()
except NoSuchElementException:
print("cant find more reviews button, continuing")

tp = targetProduct()
tp.open_page()
tp.button_click()

看起来一切正常,只是程序无法正确找到“再加载 8 条评论”按钮。我像往常一样直接从网站上复制了 xpath。是不是有什么奇怪的事情阻止我直接点击这个按钮?

最佳答案

我刚刚修改了 xpath,它正在工作。

def button_click(self):
try:
#scroll to the bottom of the page and sleep to ensure the button loads
LoadMore = self.mydriver.find_element_by_xpath("//div[@data-test='load-more-btn']/button[contains(text(),'Load')]")

sleep(3)
#click on the button to load 8 more reviews
LoadMore.click()
#sleep to load more reviews, then try clicking again to load addition reviews
sleep(3)
self.button_click()
except NoSuchElementException:
print("cant find more reviews button, continuing")

关于python - 如何使用python selenium递归地点击一个按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com