Python中的selenium网络爬虫

1 投票
2 回答
4905 浏览
提问于 2025-04-17 13:37

我想从一个有多个页面的网站上抓取数据。这些页面是动态加载的,也就是说在浏览的时候网址并没有改变。因此,我使用了selenium这个工具来抓取数据。但是,我在运行这个简单的程序时遇到了一个错误。

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 

这个问题是出在我给的网址上,还是出在火狐浏览器上呢?如果有人能帮我解决这个问题,那就太好了。

2 个回答

1

我正在开发一个Python模块,可能会适合你(或者其他人的)需求:

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

这个模块可以把录制的selenium脚本转换成爬虫函数,这样就不用自己写上面提到的代码了。它在动态加载内容的网页上效果很好。希望有人觉得这个工具有用。

1

我觉得你主要的问题是页面加载需要一些时间,而你却马上去访问那个链接(这个链接可能还没有加载出来,所以才会出现错误信息)。你可以试试使用隐式等待,这样可以让浏览器在查找元素时等一段时间,直到元素出现为止,才会停止等待。在你的情况下,你可以尝试下面的代码,这样浏览器会最多等10秒钟,同时检查页面上是否有你需要的元素(在这里是链接文本 2):

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)

撰写回答