首页 > 解决方案 > 尝试使用 selenium 单击查看更多选项卡

问题描述

我一直在使用 selenium 来抓取网站以检索一些信息。当我单击它时,该信息隐藏在使用 javascript 显示的查看更多选项卡后面。我尝试了许多不同的方法来获取可见的信息。它似乎不起作用。

我尝试使用动作链和常规的 xpath 方法将功能链接在一起,但它似乎仍然没有单击所有其他信息,并且按钮文本被打印到控制台而不是被单击。

    def grabDetails(self):
       facts = self.browser.find_elements_by_xpath("//section[@id='hdp-content']/main/div/div[4]")
       for fact in facts:
           details = fact.text
           print(details)
    def moreFeatures(self):
        view_more_elements = WebDriverWait(self.browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[contains(text(),'See More Facts and Features')]")))
        # features.click()
        ActionChains(view_more_elements).double_click().preform()
        # self.browser.execute_script('arguments[0].scrollIntoView(true);', features)

我试图从这个页面打印出来的信息! 这是我试图抓取的 zillow 页面

它下面的查看更多部分

标签: pythonselenium

解决方案


您设置view_more_elementsWebDriverWait对象而不是WebElement. 这将防止对象被点击。您只需要WebDriverWait按照自己的调用运行,然后.click()是元素。

view_more_xpath = '//div[@class="read-more zsg-centered"]/a'
view_more_elements = WebDriverWait(self.browser, 20).until(EC.visibility_of_element_located((By.XPATH, view_more_xpath))
self.browser.find_element_by_xpath(view_more_xpath).click()

编辑:您实际上不需要设置WebDriverWaitview_more_elements. 你可以这样做:

view_more_xpath = '//div[@class="read-more zsg-centered"]/a'
WebDriverWait(self.browser, 20).until(EC.visibility_of_element_located((By.XPATH, view_more_xpath))
self.browser.find_element_by_xpath(view_more_xpath).click()

推荐阅读