爬虫04作业

本次作业

  1. 爬取大数据专题所有文章列表,并输出到文本中保存。
  2. 每篇文章需要爬取的数据:作者、标题、文章地址、摘要、缩略图地址、阅读数、平均数、点赞数、打赏数。

前两次作业没成功,很大原因是自己的python环境没配置好,这次在conda的图形界面,配置了py2.7的环境,总算成功运行demo。

配置python2.7

输入demo代码

# coding: utf-8
"""
版权所有,保留所有权利,非书面许可,不得用于任何商业场景
版权事宜请联系:WilliamZeng2017@outlook.com
"""

import os
import time
import urllib2
import urlparse
from bs4 import BeautifulSoup  # 用于解析网页中文, 安装: pip install beautifulsoup4


def download(url, retry=2):
    """
    下载页面的函数,会下载完整的页面信息
    :param url: 要下载的url
    :param retry: 重试次数
    :return: 原生html
    """
    print "downloading: ", url
    # 设置header信息,模拟浏览器请求
    header = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36'
    }
    try: #爬取可能会失败,采用try-except方式来捕获处理
        request = urllib2.Request(url, headers=header) #设置请求数据
        html = urllib2.urlopen(request).read() #抓取url
    except urllib2.URLError as e: #异常处理
        print "download error: ", e.reason
        html = None
        if retry > 0: #未超过重试次数,可以继续爬取
            if hasattr(e, 'code') and 500 <= e.code < 600: #错误码范围,是请求出错才继续重试爬取
                print e.code
                return download(url, retry - 1)
    time.sleep(1) #等待1s,避免对服务器造成压力,也避免被服务器屏蔽爬取
    return html

def crawled_links(url_seed, url_root):
    """
    抓取文章链接
    :param url_seed: 下载的种子页面地址
    :param url_root: 爬取网站的根目录
    :return: 需要爬取的页面
    """
    crawled_url = set()  # 需要爬取的页面
    i = 1
    flag = True #标记是否需要继续爬取
    while flag:
        url = url_seed % i #真正爬取的页面
        i += 1 #下一次需要爬取的页面

        html = download(url) #下载页面
        if html == None: #下载页面为空,表示已爬取到最后
            break

        soup = BeautifulSoup(html, "html.parser") #格式化爬取的页面数据
        links = soup.find_all('a', {'class': 'title'}) #获取标题元素
        if links.__len__() == 0: #爬取的页面中已无有效数据,终止爬取
            flag = False

        for link in links: #获取有效的文章地址
            link = link.get('href')
            if link not in crawled_url:
                realUrl = urlparse.urljoin(url_root, link)
                crawled_url.add(realUrl)  # 记录未重复的需要爬取的页面
            else:
                print 'end'
                flag = False  # 结束抓取

    paper_num = crawled_url.__len__()
    print 'total paper num: ', paper_num
    return crawled_url

def crawled_page(crawled_url):
    """
    爬取文章内容
    :param crawled_url: 需要爬取的页面地址集合
    """
    for link in crawled_url: #按地址逐篇文章爬取
        html = download(link)
        soup = BeautifulSoup(html, "html.parser")
        title = soup.find('h1', {'class': 'title'}).text #获取文章标题
        content = soup.find('div', {'class': 'show-content'}).text #获取文章内容

        if os.path.exists('spider_res/') == False: #检查保存文件的地址
            os.mkdir('spider_res')

        file_name = 'spider_res/' + title + '.txt' #设置要保存的文件名
        if os.path.exists(file_name):
            # os.remove(file_name) # 删除文件
            continue  # 已存在的文件不再写
        file = open('spider_res/' + title + '.txt', 'wb') #写文件
        content = unicode(content).encode('utf-8', errors='ignore')
        file.write(content)
        file.close()

url_root = 'http://www.jianshu.com'
url_seed = 'http://www.jianshu.com/c/9b4685b6357c?page=%d'
crawled_links = crawled_links(url_seed,url_root)
crawled_page(crawled_links)  

输入代码后,出现如下界面。 欣喜若狂。


    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=1
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=2
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=3
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=4
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=5
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=6
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=7
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=8
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=9
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=10
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=11
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=12
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=13
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=14
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=15
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=16
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=17
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=18
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=19
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=20
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=21
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=22
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=23
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=24
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=25
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=26
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=27
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=28
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=29
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=30
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=31
    downloading:  http://www.jianshu.com/c/9b4685b6357c?page=32
    total paper num:  301
    downloading:  http://www.jianshu.com/p/45df7e3ecc78
    downloading:  http://www.jianshu.com/p/99ae5b28a51f
    downloading:  http://www.jianshu.com/p/d6243f087bd9
    downloading:  http://www.jianshu.com/p/ea40c6da9fec
    downloading:  http://www.jianshu.com/p/59e0da43136e
    downloading:  http://www.jianshu.com/p/e71e5d7223bb
    downloading:  http://www.jianshu.com/p/dc07545c6607
    downloading:  http://www.jianshu.com/p/99fd951a0b8b
    downloading:  http://www.jianshu.com/p/02f33063c258
    downloading:  http://www.jianshu.com/p/ad10d79255f8
    downloading:  http://www.jianshu.com/p/062b8dfca144
    downloading:  http://www.jianshu.com/p/cb4f8ab1b380
    


    ---------------------------------------------------------------------------

在运行时出现了此错误代码

    IOError                                   Traceback (most recent call last)

    <ipython-input-2-c1e488fdceb1> in <module>()
         99 url_seed = 'http://www.jianshu.com/c/9b4685b6357c?page=%d'
        100 crawled_links = crawled_links(url_seed,url_root)
    --> 101 crawled_page(crawled_links)
    

    <ipython-input-2-c1e488fdceb1> in crawled_page(crawled_url)
         91             # os.remove(file_name) # 删除文件
         92             continue  # 已存在的文件不再写
    ---> 93         file = open('spider_res/' + title + '.txt', 'wb') #写文件
         94         content = unicode(content).encode('utf-8', errors='ignore')
         95         file.write(content)
    

    IOError: [Errno 22] invalid mode ('wb') or filename: u'spider_res/\u5546\u4e1a\u5206\u6790\u4e4b\u6570\u636e\u8bcd\u5178| \u5f97\u5230.txt'


找到文件夹spider-res看爬虫效果:

爬好的文件

问题: 是什么原因导致,爬去中断了呢? 是代码需要更新了吗?

把错误代码输入google,答案主要有两类:1.据说是window系统下,不能使用“:”,把冒号改为破折号,但是被提示的两条错误代码中没有冒号

  1. 关于正斜杠和反斜杠的问题,应使用正斜杠,不过demo中使用的是正斜杠啊。

暂时无解。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336

推荐阅读更多精彩内容

  • 这次参照老师上课给的代码,以及查阅资料,完成的作业。 最后得到的结果中,存在了大量的转义字符。 存在问题:最后老师...
    汤尧阅读 348评论 2 0
  • 一、作业内容: 习题18-26习题18.跳过自己最难理解的17题,终于愉快地进入新篇章,向18题进军,此刻必须自我...
    小丰丰_72a2阅读 472评论 0 2
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,144评论 25 707
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,517评论 18 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,952评论 4 60