硒与python网络爬虫

时间:2013-01-25 05:40:03

标签: python selenium web-crawler

我想屏幕抓一个有多个页面的网站。这些页面是动态加载的,无需更改URL。因此,我正在使用硒来筛选它。但是我对这个简单的程序有例外。

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浏览器的问题。 如果有人帮助过我会有很大的帮助。

2 个答案:

答案 0 :(得分:1)

我认为您的主要问题是页面本身需要一段时间才能加载,并且您正在尝试访问该链接(可能尚未呈现,因此堆栈跟踪)。您可以尝试的一件事是使用隐式等待1browser,这将告诉browser在超时之前等待元素出现的特定时间段。在您的情况下,您可以尝试以下操作,在轮询特定项目的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)

答案 1 :(得分:1)

我正在开发一个可能涵盖你(或其他人)用例的python模块:

https://github.com/cmwslw/selenium-crawler

它将记录的selenium脚本转换为爬行函数,从而避免编写上述任何代码。它适用于动态加载内容的页面。我希望有人觉得这很有用。