Selenium 似乎无法在网站上找到并单击按钮? - Python

Selenium can't seem to find and click a button on website? - Python

我正在尝试制作可以从 fiverr.com 网站自动为我收集数据的软件。

它搜索特定的术语,然后它应该按页面末尾的 LOAD MORE 按钮,并一直单击它直到它加载所有 'gigs'。

无论如何,我很清楚如何让它一直点击直到所有内容都加载完毕,但我似乎什至无法点击它。

这是我选择按钮并单击它的代码:

driver.find_element_by_xpath('//*[@class="btn-standard-lrg btn-white"]').click()

我不断收到以下错误:

Element is not currently visible and so may not be interacted with

如果您转到:fiverr gig url 并向下滚动,您可以看到加载更多按钮。

首先,像btn-standard-lrgbtn-white那样使用"layout-oriented"或"design-oriented"类是一种不好的做法。

相反,有一个方便的定位器 "by link text",使用它:

load_more = driver.find_element_by_link_text("LOAD MORE")

注意它的可读性和简单性。


您可能还需要 wait until the "Load More" button would become visible:

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(driver, 10)
load_more = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, 'LOAD MORE')))

而且,这里是完整的代码,点击 "Load More" 直到它变得不可见,这意味着所有帖子都已加载:

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException


driver = webdriver.Chrome()  # or webdriver.Firefox()
driver.get("https://www.fiverr.com/search/gigs?utf8=%E2%9C%93&search_in=everywhere&source=top-bar&query=explainer%20video&page=1&layout=lists&filter=new")

wait = WebDriverWait(driver, 10)
while True:
    try:
        load_more = wait.until(EC.visibility_of_element_located((By.LINK_TEXT, 'LOAD MORE')))
    except TimeoutException:
        break

    load_more.click()

for item in driver.find_elements_by_css_selector("div.gig-item h3 a.gig-link-main"):
    print item.text.strip()

这似乎是一个问题,因为您正在尝试与页面中不可见的元素进行交互(您需要向下滚动到页面底部才能看到它)...

尝试做这样的事情:

element = driver.find_element_by_xpath('//*[@class="btn-standard-lrg btn-white"]')

location = element.native.location[:y]

execute_script("window.scrollTo(0, #{location})")

element.click

或者在点击滚动到页面底部之前:

execute_script("window.scrollTo(0, 10000)")

查看该网站似乎正在进行一些游戏。根据经验,我建议:

一般:

  1. 不要屏蔽来自第 3 方网站的抓取信息。如果他们更改网站,您的代码将被破坏 - 也许联系该网站,看看他们是否有 API?
  2. 始终使用 PageObject 模式,因为它会让您的代码保持干燥(考虑组件而不是 'pages')。

具体:

  1. 先尝试选择一个父元素,然后再选择您想要的元素。这通常会导致您遇到问题。
  2. 如果您没有在 selenium 中配置任何自动重试,您可以在元素可见之前 运行 该代码。正如您从错误消息中看到的那样,该元素在那里只是不可见(我有 selenium 经验,但很少 python 所以无法帮助您 :-( ).