美文网首页程序员
网络爬虫之reddit爬取-后续

网络爬虫之reddit爬取-后续

作者: Ydrivemecrazy | 来源:发表于2017-08-16 04:43 被阅读0次

之前写的那个reddit爬取不含细节,因为我最后爬取没有采用爬取所有的小板块,而是采取了从网页
https://www.reddit.com/r/Wishlist/search?q=flair%3A%27chat%27&restrict_sr=on&sort=new&feature=legacy_search&count=26&before=t3_6omz4l
开始爬取,现在把这个的爬取过程和代码写下来,含较多细节,想直接要数据的也可以私信我,不过新手的话爬一下也正好学习一下不是吗?

准备工作

注:不熟悉scrapy的朋友还是看我上一篇文章推荐的两个链接先熟悉一下。
不熟悉爬取技巧的也推荐看一下

1. 确定爬取的起始网页

网站的开始页面为上图所示。
所以start_url为该页面的url:
https://www.reddit.com/r/Wishlist/search?q=flair%3A%27chat%27&restrict_sr=on&sort=new&feature=legacy_search&count=26&before=t3_6omz4l

2. 如何获取下一页

用Firebug工具使用点击查看next按钮这个元素,如下图所示。

右键点击复制xpath得到xpath:

/html/body/div[5]/div[4]/div[51]/span/span/a

结合图中html中的显示:

<a href="略" rel="nofollow next">next ›</a>

获取方式为:

next_page  = selector.xpath('//a[@rel="nofollow next"]/@href').extract() 

3. 如何获取图中每个小块跳转到的链接页面

以第一个[Chat] August 15, 2017为例:
同样用Firebug工具使用点击查看这个元素同时右键复制xpath,得到在

  1. 在html中的显示:

     <a class="title may-blank " data-event-action="title" href="/r/Wishlist/comments/6tt6vs/chat_august_15_2017/" ...>略</a>
     # 而跳转到的网页的url如下
     https://www.reddit.com/r/Wishlist/comments/6tt6vs/chat_august_15_2017/
    

可以看出是 https://www.reddit.com + href中的内容组合而成

  1. xpath为:

     /html/body/div[5]/div[4]/div[1]/div[2]/div[1]/p[1]/a
    

获取方式为:

comment_page  = selector.xpath('//a[@data-event-action="title"]/@href').extract() 

4. 如何获取界面中的每一组谈话

上一步获取的界面为下图所示

首先获取最上面的开始话题的那一句话

xpath为:/html/body/div[5]/div[1]/div[1]/div[2]/div[2]/form/div/div/p

然后获取下面每一个小块区域中的话

第一种方法:

comment_zone = selector.xpath('//div[@data-type="comment"]')

然后

for conversation in comment_zone:
    talk = conversation.xpath('//div[@class="usertext-body may-blank-within md-container "]/div/p/text()').extract()

这样还是不能解决对话的逻辑问题。

第二种方法:
需要更仔细的观察html结构,可以利用一种深度优先搜索的感觉。
先看一下xpath:
最外面:

/html/body/div[5]/div[2]/div[3]/

第一层:

/html/body/div[5]/div[2]/div[3]/+div[*]/+div[2]/form/div/div/p

第二层:

/html/body/div[5]/div[2]/div[3]/+div[*]/+div[3]/div/div[*]/+div[2]/form/div/div/p

第三层:

/html/body/div[5]/div[2]/div[3]/+div[*]/+div[3]/div/div[*]/+div[3]/div/div[*]/+div[2]/form/div/div/p

找到了规律。
然后结合在html中的表示,现在贴上代码,进行解释:

  1. 获取每个小块跳转到的链接页面,然后调用parse_page
  1. 然后利用递归的思想。
    parse_page为入口,负责获取最上面的开始话题的那一句话和调用parse_zone
    parse_zone为一个递归函数,当不再有向下的评论时便返回itemitem里面存的是对话序列,否则就继续调用,反正就是个深度优先搜索的感觉,不过互不影响所以可以并行地爬取。
    注:这里需要特别说明的是,meta是一个scrapy用来传递参数的方法,还是比较有用的,传递的是一个字典。然后对于正则表达式和一些编码的问题,希望读者也可以自己去耐心了解。

     def parse_zone(self, response):
     # 采用递归思想,相当于一个深度优先搜索
     pre_path = response.meta['pre_path'][:]
     pre_comment_list = response.meta['pre_comment_list'][:]
     now_layer_spec = response.selector.xpath(pre_path +'div[@class="child"]/div[@class="sitetable listing"]/div[*]/div[@class="entry unvoted"]//div[@class="md"]/p[1]').extract()
     if len(now_layer_spec)>0:
         i = 1
         for spec in now_layer_spec:
             if len(spec)<1:
                 break
             next_layer_path = pre_path + 'div[@class="child"]/div[@class="sitetable listing"]/div['+str(i)+']/'
             now_comment_list = pre_comment_list[:]
             tmp_conv = re.sub("a href(.*?)</a>",'',str(spec).encode('unicode_escape').strip('<p>').strip('</p>'))
             now_comment_list.append(tmp_conv)
             yield scrapy.http.Request(str(response.url), callback=self.parse_zone, meta={'pre_path':next_layer_path[:], 'pre_comment_list':now_comment_list[:]}, dont_filter=True)
             i += 2
     else:
         item = RedditItem()
         item['talks'] = pre_comment_list[:]
         yield item
    
     def parse_page(self, response):
     # 获取最上面的开始话题的那一句话
     first_talk = response.selector.xpath('//div[@id="siteTable"]/div[@data-context="comments"]/div[@class="entry unvoted"]//div[@class="md"]/p[1]').extract()
     # 获取下面每一个小块区域
     comment_zone = response.selector.xpath('//div[@class="commentarea"]/div[@class="sitetable nestedlisting"]/div[*]/div[@class="entry unvoted"]//div[@class="md"]/p[1]').extract()
     i = 1
     for convers in comment_zone:
         if len(convers) <1:
             break
         next_layer_path = '//div[@class="commentarea"]/div[3]/' + 'div['+str(i)+']/'
         tmp_list=[]
         tmp_conv1 = re.sub("a href(.*?)</a>",'',str(first_talk[0]).encode('unicode_escape').strip('<p>').strip('</p>'))
         tmp_list.append(tmp_conv1)
         tmp_conv2 = re.sub("a href(.*?)</a>",'',str(convers).encode('unicode_escape').strip('<p>').strip('</p>'))
         tmp_list.append(tmp_conv2)
         yield scrapy.http.Request(str(response.url), callback=self.parse_zone, meta={'pre_path':next_layer_path[:], 'pre_comment_list':tmp_list[:]}, dont_filter=True)
         i += 2
    

自认为写的还算明白,也就不再做过多解释了。

开始爬取

准备工作差不多了,剩下的事情就是按照scrapy的框架写一下其它文件,然后放到服务器上跑了,至于服务器的相关问题可以看我之前的文章。

最近在看神经网络的事情,所以之前的文章有不全面的也暂时不更新了。

相关文章

网友评论

    本文标题:网络爬虫之reddit爬取-后续

    本文链接:https://www.haomeiwen.com/subject/hppbrxtx.html