python - Selenium 提取问题 : Waits/Not Finding Elements

标签 python css selenium web-scraping

在 chrome 和 firefox 中,一切都很好,直到我需要提取文本。我收到此错误:

h3 = next(element for element in h3s if element.is_displayed())
StopIteration

我什至添加了流畅的等待。

browser = webdriver.Firefox()
browser.get('https://www.voilanorbert.com/')
inputElement = browser.find_element_by_id("form-search-name")
inputElement.send_keys(leadslist[i][0])
inputElement = browser.find_element_by_id("form-search-domain")
inputElement.send_keys(leadslist[i][1])
searchbutton = browser.find_element_by_name("search")
searchbutton.click()

wait = WebDriverWait(browser, 20)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.results")))
wait2 = WebDriverWait(browser, 3000, poll_frequency=100, ignored_exceptions=[ElementNotVisibleException])
wait2.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "h3.one")))
h3s = browser.find_elements_by_css_selector('h3.one')
h3 = next(element for element in h3s if element.is_displayed())
result = h3.text

我认为这是因为它实际上并没有提取任何东西,所以它只是一个空列表。 一些可能会有所帮助的图片: 这是之前的图: enter image description here

这是后图: enter image description here

我需要提取“result”类的“text-center displayed”类中的内容。

enter image description here

最佳答案

答案很简单,您只需要在等待搜索结果时使用不同的选择器即可。 下面的方法 (C#) 工作得很好,它会减少几行代码。

搜索完成后,一个“结果 DIV”将变为可见。它是唯一具有“文本中心显示”类的元素,所以这就是您的选择器所需要的。 一旦显示了这样的 DIV,您就知道在何处精确定位 H3 元素(它是上述 DIV 的子元素)。 因此,只需等待以下元素在您单击搜索按钮后变得可见即可:

        IWebElement headerResult = w.Until(ExpectedConditions.ElementIsVisible(By.CssSelector("div[class=\"text-center displayed\"] h3")));
        string result = headerResult.Text;

关于python - Selenium 提取问题 : Waits/Not Finding Elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29522924/

相关文章:

python - 如果引发异常,如何使 Flask-SQLAlchemy 自动回滚 session ?

python - 为 Django 设置 SQLite3 时出现错误配置的数据库错误

python - 解释器何时释放模块作用域变量引用?

jquery - 在 jQuery 中交替非连续行颜色

javascript - jQuery Isotope 第一次过滤似乎不起作用

python - 返回全部一起而不是 1×1

java - 尝试使用 Hudson 运行 Selenium 测试 - "Error: no display specified"

c++ - 如何编写程序重命名 mp4 文件以匹配 srt 文件的名称?

javascript - 如何让 {{#each}} 使用这些模板?

java - WebElements 列表中的相对 Xpath