scrapy简单爬取大话西游论坛文本

目标:登录大话西游论坛入口网站http://dhxy.netease.com/forum-39-1.html 自定义页数爬取

这个版块
的所有具有
版主回复
标志的帖子的文本内容

工具:scrapy框架
思路:获取start_urls 网页内容,获取帖子链接,存入数组,将帖子链接一个一个传递给parse_content 函数解析内容,parse_content生成字典并且获取下一页链接,回调parse函数,重新进行下一页的爬取

代码实现:

创建项目:scrapy startporject dhxy_luntan
根据提示创建 spider

spider.py

# -*- coding: utf-8 -*-
import scrapy
import re
import sys
from scrapy.http import Request
from dhxy_luntan.items import DhxyLuntanItem
reload(sys)
sys.setdefaultencoding('utf-8')

class DhxyLuntanSpiderSpider(scrapy.Spider):
    name = "dhxy_luntan_spider"
    #allowed_domains = ["http://dhxy.netease.com/forum-39-1.html"]
    start_urls = (
        'http://dhxy.netease.com/forum-39-1.html',
    )

    def parse(self, response):
        urls = []
        sel = scrapy.Selector(response)
        content = sel.xpath('//*[@id="threadlist"]/div[2]/form/table/tbody[starts-with(@id,"normalthread_")]/tr/th').extract()
        print len(content)
        str_ = u'版主回复'
        qiandao_ = u'签到'
        for i in content:       
            if str_ in i:
                hrefs = re.findall('</em> <a href="(.*?)" .*?onclick.*?</a>', i, re.S)
                if hrefs:
                    href = hrefs[0]
                    full_href = 'http://dhxy.netease.com/' + href
                    urls.append(full_href)
        for i in urls:
            yield Request(i, callback=self.parse_content)
    def parse_content(self, response):
        item = DhxyLuntanItem()
        sel = scrapy.Selector(response)
        title  = sel.xpath('//*[@id="thread_subject"]/text()').extract()[0]
        item['url'] = u'\n['+title + u']' + response.url
        data = sel.xpath('//tr/td[starts-with(@id, "postmessage")]')
        content = data.xpath('string(.)').extract()  #string(.) 当前层的所有内容作为一个字符串输出
        if content:
            item['content'] = content
            yield item
        for i in range(2,5):   
            next_page = 'http://dhxy.netease.com/forum-39-' + str(i) + '.html'
            yield scrapy.http.Request(next_page, callback = self.parse)


items.py

Paste_Image.png

setting.py
因为需要输出csv格式,在setting文件中设置


Paste_Image.png

pipeline.py
不用保存到数据库pipeline无需设置

运行代码:scrapy crawl dhxy_luntan_spider
生成csv文件:

Paste_Image.png

使用excel的导出功能,更改文件类型:

Paste_Image.png

特殊字符可在编辑器中替换,?分析为&nbsp(html 里是空格占位符,普通的空格在 html 里如果连续的多个可能被认为只有一个,而这个东西你写几个就能占几个空格位)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • scrapy学习笔记(有示例版) 我的博客 scrapy学习笔记1.使用scrapy1.1创建工程1.2创建爬虫模...
    陈思煜阅读 14,374评论 4 46
  • 这两天摸索了下scrapy,刚看文档的时候觉得有点生无可恋,scrapy框架个人还是觉得比较难懂的,需要学习的地方...
    Treehl阅读 10,969评论 7 10
  • 序言第1章 Scrapy介绍第2章 理解HTML和XPath第3章 爬虫基础第4章 从Scrapy到移动应用第5章...
    SeanCheney阅读 15,224评论 13 61
  • scrapy是python最有名的爬虫框架之一,可以很方便的进行web抓取,并且提供了很强的定制型,这里记录简单学...
    bomo阅读 6,521评论 1 11
  • 今天分享会由唐分享,主题是她最近看的《怪诞心理学》。她还是比较用心的,书看得比较仔细,做了归纳,说了认为有趣的。不...
    xxwade阅读 3,321评论 0 2