【问题标题】:Web scraping using selenium in python, trouble in click the button在python中使用selenium进行网页抓取,点击按钮时遇到麻烦
【发布时间】:2021-01-15 00:25:49
【问题描述】:

我正在从 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"> 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选择器也不好用。

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

非常感谢!

【问题讨论】:

    标签: python selenium button web-scraping


    【解决方案1】:

    这是一个连续单击该元素的示例。

    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 等待允许您等到元素可点击,它还会轮询 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
    

    【讨论】:

    • 非常感谢。对我来说效果很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 1970-01-01
    • 2021-05-08
    • 2018-07-20
    • 2020-03-13
    相关资源
    最近更新 更多