爬虫03作业。(没有成功)

作业背景:
这是被卡得煎熬的一次作业,我反复把课上的内容听了,感觉还是无法下手。 本计划仿制另外一个同学的代码的,发现他作业中单独定义了很多.py的文件,这个我就仿制不了。

于是,再换了一种思路,使用小密圈代码。 小密圈代码并非完整版。

于是再换思路, 仿制爬虫课上的ppt代码。 又遇到python环境不兼容的问题,老师的代码基于py2,我的环境是py3。 本计划通过Google,把py2代码替换为py3,结果只完成了一小部分。 google时发现,stock overflow真的很强大,几乎每一个代码的错误反馈,stock overflow几乎都有相关答案,只不过是英文的,不太好消化。

无奈今晚要上课了,只能先提交半成品,证明我努力过。

希望爬虫课的课后资料,能够更贴近0基础人群些。 现在的困扰是,课后很难复现老师的代码。这样难有正反馈。

以下是代码流程

# -*- coding: utf-8 -*-
import os
import time
from urllib.request import urlopen
from urllib.parse import urlparse
from bs4 import BeautifulSoup 


# 我这个情况,是不是没有安装urllib2的库啊?
# -*- coding: utf-8 -*-
import os
import time
from urllib.request import urlopen
from urllib.parse import urlparse
from bs4 import BeautifulSoup 
html = urlopen("http://www.jianshu.com/p/aa1121232dfd")
print (html)

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) #设置请求数据
        request = urllib.request.Request(url, headers=header)
        html = urllib.request.urlopen(request).read() #抓取url
    except urllib.request.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/p/aa1121232dfd?page=%d'


crawled_url = set()

flag = True

关于爬虫3课中的demo代码问题。

背景:想要重复曾老师爬虫课上的代码,我是用的是小密圈分析的那段段代码,把打头前几段输入就开始报错,主要是这两句,在报错

  1. import urllib2
  2. import urlparse。
    研究后发现,问题是由于老师的代码是基于python2,我的环境是python3,使得代码报错,
    google后将这两段代码换为
  3. from urllib.request import urlopen
  4. from urllib.parse import urlparse
    就正常了。

问题是:

  1. 除了我发现的两句要替换成python3的格式外,后面的代码,有没有也需要做相应替换的?
  2. 老师第三课上的ppt代码,和小密圈分享的代码,是不一样的,小密圈代码,是不是只定义了几个函数而已,是不能做爬取的?
  3. 如果我复现了课上ppt的代码,是不是就能把作业解出来?

ps:真的卡住了,自己实在干不动了,真心求助啊。

i = 1
while flag:
    ##url = url_seed%1
    url = url_seed.format(1)
    i += 1
    
    html =download(url)
    if html==None:
        break
        
    soap = BeautifulSoup(html,"html.parser")
    links =soap.find_all('a',{'class':'title'})
    if links.__len__()==0:
        flag = False
        
for link in links:
    link = link.get('herf')
    if link not in crawled_url:
        realUrl = urlparse.urljoin(url_root,link)
        crawled_url.add(realUrl)
        
    else:
        print('end') 
        flag =False
        
downloading: 



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

NameError                                 Traceback (most recent call last)

 in download(url, retry)
     14         ##request = urllib2.Request(url, headers=header) #设置请求数据
---> 15         request = urllib.request.Request(url, headers=header)
     16         html = urllib.request.urlopen(request).read() #抓取url


NameError: name 'urllib' is not defined


During handling of the above exception, another exception occurred:


NameError                                 Traceback (most recent call last)

 in ()
      5     i += 1
      6 
----> 7     html =download(url)
      8     if html==None:
      9         break


 in download(url, retry)
     15         request = urllib.request.Request(url, headers=header)
     16         html = urllib.request.urlopen(request).read() #抓取url
---> 17     except urllib.request.URLError as e: #异常处理
     18         print ("download error: ", 'e.reason')
     19         html = None


NameError: name 'urllib' is not defined

再次卡住

现在遇到的问题是,代码中那些基于py2环境的urllib2,应切换成什么样的代码,这是个问题。 我尝试把urllib2替换为urllib.request,均无效。

我觉得目前,自己的解决方法,有两种:

  1. 把所有基于py2的代码替换为py3格式
  2. 新建python2的环境。
    做第一件事,对学习价值更大。
    做第二件事,能更快地获得正反馈。

可是这次的作业怎么办,我觉得,应该照着,把代码补齐,然后先提交作业。就像参加长跑比赛的运动员,可能前三名已经出现了,自己还是应该跑完。

paper_num = crawled_url.--len__()
print('total paper num':,paper_num)
#此处是修改为py3语法

  File "", line 1
    paper_num = crawled_url.--len__()
                            ^
SyntaxError: invalid syntax

对了,py3的print跟py2不一样,py3是print("")模式

for link in crawled_url:
    html = download(link)
    soap = BeautifulSoup(html,"html.parser")
    title = soap.find('h1',{"class":"title"}).txt
    content = soap.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):
        continue
    file = open('spider_res'+title+'.txt','wb')
    content = unicode(content).encode('utf-8',errors='ignore')
    file.write(content)
    file.close()
    
  File "", line 1
    for link in crawled_url:
                           ^
SyntaxError: invalid character in identifier


你可能感兴趣的:(爬虫03作业。(没有成功))