【问题标题】:Use scrapy with selenium for dynamic pages对动态页面使用带有 selenium 的 scrapy
【发布时间】:2016-10-13 16:40:13
【问题描述】:

我想为所有参展商抓取此页面:

https://greenbuildexpo.com/Attendee/Expohall/Exhibitors

但是scrapy不加载内容,我现在正在做的是使用selenium来加载页面并用scrapy搜索链接:

url = 'https://greenbuildexpo.com/Attendee/Expohall/Exhibitors'

driver_1 = webdriver.Firefox()
driver_1.get(url)
content = driver_1.page_source

response = TextResponse(url='',body=content,encoding='utf-8')
print len(set(response.xpath('//*[contains(@href,"Attendee/")]//@href').extract()))

当按下“下一步”按钮时,该网站似乎没有发出任何新请求,所以我希望同时获得所有链接,但我只获得了 43 个带有该代码的链接。他们应该在 500 左右。

现在我正在尝试通过按“下一步”按钮来抓取页面:

for i in range(10):
    xpath = '//*[@id="pagingNormalView"]/ul/li[15]'
    driver_1.find_element_by_xpath(xpath).click()

但我得到了一个错误:

File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 192, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: {"method":"xpath","selector":"//*[@id=\"pagingNormalView\"]/ul/li[15]"}
Stacktrace:

【问题讨论】:

    标签: python selenium xpath scrapy


    【解决方案1】:

    你不需要selenium,有一个XHR请求来获取所有参展商,模拟它,来自Scrapy Shell的演示:

    $ scrapy shell https://greenbuildexpo.com/Attendee/Expohall/Exhibitors
    In [1]: fetch("https://greenbuildexpo.com/Attendee/ExpoHall/GetAllExhibitors")
    2016-10-13 12:45:46 [scrapy] DEBUG: Crawled (200) <GET https://greenbuildexpo.com/Attendee/ExpoHall/GetAllExhibitors> (referer: None)
    
    In [2]: import json
    
    In [3]: data = json.loads(response.body)
    
    In [4]: len(data["Data"])
    Out[4]: 541
    
    # printing booth number for demonstration purposes
    In [5]: for item in data["Data"]:
       ...:     print(item["BoothNumber"])
       ...:  
    2309
    2507
    ...
    1243
    2203
    943
    

    【讨论】:

      猜你喜欢
      • 2013-08-01
      • 2019-10-27
      • 2022-01-08
      • 2021-12-10
      • 1970-01-01
      • 2017-12-22
      • 2015-04-02
      • 1970-01-01
      • 2013-05-07
      相关资源
      最近更新 更多