2016-12-07 127 views
0

我正要抓取一个加载了javascript和PHP的网页。 因此我将Scrapy代码与Selenium混合使用。但由于我不知道的原因, 代码不断出错。Scrapy + Selenium混合代码产生错误

我想刮的页面是http://ntry.com/#/scores/named_ladder/main.php, 可以通过点击一个按钮,它的文本元素U“사다리”到达,从 ntry.com。我使用了Firefox Selenium插件,并记录进入ntry.com,点击按钮,到达要被抓取的页面,并使用从记录中删除的代码。

所以,我做了一个蜘蛛文件混合硒代码。

# encoding=utf-8 
import unittest, time, re 
import scrapy 
from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.support.ui import Select 

from pyvirtualdisplay import Display 

display = Display(visible=0, size=(1024, 768)) 
display.start() 

class NTRYSpider(scrapy.Spider): 
    name = "ntryspider" 
    allowed_domains = ["www.ntry.com"] 
    start_urls = [ 
     "http://ntry.com" 
    ] 

    def __init__(self): 
     scrapy.Spider.__init__(self) 
     self.driver = webdriver.Firefox() 

    def parse(self, response): 

     self.driver.get(response.url + "/#/main.php") 
     self.driver.find_element_by_link_text(u"사다리").click() 
     time.sleep(5) 

     html =self.driver.find_element_by_xpath('//*').get_attribute('outerHTML') 
    print html 
    display.stop() 

,这使得错误是这样的: File "/home/ubuntu/ntry_virtualenv/local/lib/python2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 236, in execute self.error_handler.check_response(response) File "/home/ubuntu/ntry_virtualenv/local/lib/python2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response raise exception_class(message, screen, stacktrace) NoSuchElementException: Message: Unable to locate element: \uc0ac\ub2e4\ub9ac 不仅关系到错误信息,有没有在上面的代码中的任何可能出现的问题? 我错过了什么元素?我该怎么办?

我使用Ubuntu的无头与14.04最新和兼容pyvirtualdisplay,XVFB,火狐,webdriver的,..等。

顺便说一句,firefox的插件硒生成的代码如下图所示:sweat_smile:

class PythonNtry(unittest.TestCase): 
    def setUp(self): 
     self.driver = webdriver.Firefox() 
     self.driver.implicitly_wait(30) 
     self.base_url = "http://ntry.com/" 
     self.verificationErrors = [] 
     self.accept_next_alert = True 

    def test_python_ntry(self): 
     driver = self.driver 
     driver.get(self.base_url + "/#/main.php") 
     # ERROR: Caught exception [ERROR: Unsupported command [selectFrame | contentFrame | ]] 
     driver.find_element_by_link_text(u"사다리").click() 

回答

0

这条线是有缺陷:

driver.find_element_by_link_text(u"사다리").click() 

find_element_by_link_text()返回硒web对象,如果它可以发现,否则返回None。这里发生的是没有元素被找到,你可以拨打click()。为了解决这个问题,您可以将其安全地包裹进去:

element = driver.find_element_by_link_text(u"사다리") 
if element: 
    element.click() 
else: 
    print('element not found!')