python - selenium 与 python 网络爬虫

标签 python selenium web-crawler

我想屏幕抓取具有多个页面的网站。这些页面是动态加载的,无需更改 URL。因此我使用 Selenium 来筛选它。但我在这个简单的程序中遇到了异常(exception)。

import re
from contextlib import closing
from selenium.webdriver import Firefox 

url="http://www.samsung.com/in/consumer/mobile-phone/mobile-phone/smartphone/"

with closing(Firefox()) as browser:
    n = 2
    link = browser.find_element_by_link_text(str(n))
    link.click()
    #web_page=browser.page_source
    #print type(web_page)

错误如下

raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: u'Unable to locate element: {"method":"link text","selector":"2"}' ; Stacktrace: Method FirefoxDriver.prototype.findElementInternal_ threw an error in file:///tmp/tmpMJeeTr/extensions/fxdriver@googlecode.com/components/driver_component.js 

是给定的url问题还是firefox浏览器的问题。 如果有人帮助我,那就太好了。

最佳答案

我认为您的主要问题是页面本身需要一段时间才能加载,并且您立即尝试访问该链接(可能尚未呈现,因此堆栈跟踪)。您可以尝试的一件事是使用隐式等待 1使用您的浏览器,这将告诉浏览器在超时之前等待一段时间以便元素出现。在您的情况下,您可以尝试以下操作,这将在轮询 DOM 中查找特定项目(在本例中为链接文本 2)时等待最多 10 秒:

browser.implicitly_wait(10)
n = 2
link = browser.find_element_by_link_text(str(n))
link.click()
#web_page=browser.page_source
#print type(web_page)

关于python - selenium 与 python 网络爬虫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14516014/

相关文章:

python - 为什么在这种特殊情况下使用生成器对象?

python - 如何在python中创建一个每天枚举的循环?

java - 为什么我的代码不能正常工作?

python - 如何从 url 列表中查找有多少 url 正在运行

java - 如何确定 WebElement 是否存在于 Selenium 中?

python - 如何使用python获取整个网站的所有页面?

python - 获取selenium中具有相同类名的所有值

python - 将 NumPy 数组按元素映射到更多维度的数组

python - 在 Python 代码中标记 "print"语句

Python3.3 HTML Client TypeError : 'str' does not support the buffer interface