在python中使用selenium进行Web抓取,单击按钮会出现问题

2024-06-02 08:16:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从Wayfair(如https://www.wayfair.com/appliances/pdp/bissell-aeroswift-compact-bagless-vacuum-bse10083.html)中删除客户评论。但是,第一页上只列出了3条评论,我需要使用Selenium不断“点击”按钮“显示10条更多评论”

与按钮对应的html是:<button data-hb-id="pl_button" class="Button Button--alternate Button--large Button--plainText" type="button"><span class="Button-content"><span><span class="pl-LoadingButton-content is-entered" style="transition: opacity 500ms ease-in-out 0s;"><div class="pl-Box--display-flex" data-hb-id="pl-box">Show 10 More<span class="SeeMoreReviewsButton-reviewsText">&nbsp;Reviews</span><svg focusable="false" viewBox="0 0 28 28" class="pl-BaseIcon pl-BaseIcon--scalable" aria-hidden="true" data-hb-id="pl-icon"><path d="M14 19a.47.47 0 01-.35-.15l-7-7a.49.49 0 01.7-.7L14 17.79l6.65-6.64a.49.49 0 11.7.7l-7 7A.47.47 0 0114 19z"></path></svg></div></span></span></span></button>

我已经尝试过使用find_element_by_xPath,但xPath在多次单击后保持更改:

element = browser.find_element_by_xpath('//*[@id="bd"]/div[2]/div[2]/div[1]/div/div/div/div/div/div[5]/div/div/button') 
element.click()

变量xPath包括:

//*[@id="bd"]/div[2]/div[2]/div[1]/div/div/div/div/div/div[5]/div/div/button
//*[@id="bd"]/div[2]/div[2]/div[1]/div/div/div/div/div/div[5]/div[1]/div/button
//*[@id="bd"]/div[2]/div[2]/div[1]/div/div/div/div/div/div[4]/div/div/button

另一种查找元素的方法,如按类和按css选择器,也不能很好地工作

有人知道我应该如何获取按钮元素并单击它吗

非常感谢


Tags: dividdatahtml评论buttonelement按钮
1条回答
网友
1楼 · 发布于 2024-06-02 08:16:31

下面是一个连续单击该元素的示例

url = "https://www.wayfair.com/appliances/pdp/bissell-aeroswift-compact-bagless-vacuum-bse10083.html"
driver.get(url)
wait = WebDriverWait(driver,10)
while True:
    try:
        wait.until(EC.element_to_be_clickable((By.XPATH,"//*[text()='Show 10 More']/ancestor::button" ))).click()
    except Exception as e:
        print(e)
        break

您经常需要检查是否可以单击按钮,然后在出现错误时中断循环。Webdriver Waitis允许您等待,直到元素可单击,并且它还轮询dom以使元素也在其中

进口

from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

相关问题 更多 >