如何从无限滚动网站刮取所有内容? scrapy

时间:2016-05-13 10:43:57

标签: python web-scraping scrapy web-crawler sitemap

我正在使用scrapy。

我正在使用的网站有无限滚动。

该网站有很多帖子,但我只抓了13个。

如何刮掉其余帖子?

这是我的代码:

class exampleSpider(scrapy.Spider):
name = "example"
#from_date = datetime.date.today() - datetime.timedelta(6*365/12)
allowed_domains = ["example.com"]
start_urls = [
    "http://www.example.com/somethinghere/"
]

def parse(self, response):
  for href in response.xpath("//*[@id='page-wrap']/div/div/div/section[2]/div/div/div/div[3]/ul/li/div/h1/a/@href"):
    url = response.urljoin(href.extract())
    yield scrapy.Request(url, callback=self.parse_dir_contents)


def parse_dir_contents(self, response):
    #scrape contents code here

6 个答案:

答案 0 :(得分:3)

我使用的是datetime而不是Selenium,但你必须能够做同等的事情,而我所做的就是在加载文件时运行一些JavaScript,即:

scrapy

我一直这样做,直到它不再滚动为止。它不漂亮,不能用于生产,但对特定的工作有效。

答案 1 :(得分:2)

我认为您正在寻找的是与您的正常逻辑相关的分页逻辑

在大多数情况下.. 无限滚动==分页,在此页面上向下滚动到页面的3/4或直到页面末尾时,页面会触发AJAX调用并下载下载页面内容并将响应加载到当前页面

我建议在firefox中使用<select> <option <?PHP echo ($day=='Tuesday' ? selected : ""); ?>>Tuesday</option> </select> 工具,并在向下滚动时注意任何此类页面请求

- 线索:在实施此解决方案时,您将使用scrapy.FormRequestscrapy.FormRequest.from_response

答案 2 :(得分:2)

检查网站代码。

如果无限滚动自动触发js操作,您可以使用Alioth提案进行如下操作:spynner

在spynner docs之后,你会发现它可以触发jquery事件。

  

查找库代码以查看可以触发的事件类型。

尝试在网站的可滚动内容中的任何div上生成滚动到底部事件或创建css属性更改。关注spynner docs,类似于:

browser = spynner.Browser(debug_level=spynner.DEBUG, debug_stream=debug_stream)
# load here your website as spynner allows
browser.load_jquery(True)
ret = run_debug(browser.runjs,'window.scrollTo(0, document.body.scrollHeight);console.log(''scrolling...);')
# continue parsing ret 

无法通过锚链接触发无限滚动,但也许可以通过jquery动作触发,而不是连接到链接的necesarry。对于这种情况,请使用以下代码:

br.load('http://pypi.python.org/pypi')

anchors = br.webframe.findAllElements('#menu ul.level-two a')
# chooses an anchor with Browse word as key
anchor = [a for a in anchors if 'Browse' in a.toPlainText()][0]
br.wk_click_element_link(anchor, timeout=10)
output = br.show()
# save output in file: output.html or 
# plug this actions into your scrapy method and parse output var as you do 
# with response body

然后,在output.html文件上运行scrapy,或者,如果你实现了它,使用你选择在js操作后存储修改后的html的本地内存变量。

作为另一种解决方案,您尝试解析的网站可能具有备用呈现版本,以防访问者浏览器未激活 js。

尝试使用禁用javascript的浏览器呈现网站,也许这样,网站会在内容部分的末尾提供锚链接。

还有成功的实现了爬虫js导航,使用Scrapy方法和this中详细介绍的Selenium来回答。

答案 3 :(得分:1)

答案 4 :(得分:1)

显然,该目标网站动态上传其内容 。因此,有两种适当的解决方案:

  1. 解密微妙的jQuery交互并尝试模拟与服务器manually的数据交换

  2. 为此特定作业使用其他工具。例如spynner在我看来是一个正确的选择。

答案 5 :(得分:0)

在某些情况下,即使在无限滚动中,您也可以在源代码中找到称为“下一个”分页运行的元素。因此,您只需单击此元素,它将显示其余的帖子。带有草皮/硒:

next = self.driver.find_element_by_xpath('//a[@class="nextResults"]')
next.click()
time.sleep(2) 
相关问题