python3爬虫下载网页上的pdf

来源:互联网 发布:excel对比两列数据异同 编辑:程序博客网 时间:2024/06/06 01:33


今天在网上看一个课程的讲义,每次都点pdf打开什么的有点麻烦,就想着用爬虫把他们都下载下来。虽然网上资料很多,但毕竟python不是很熟,期间遇到好多问题,不过最终也下载完成了。

主要参考了

1 http://blog.csdn.net/baidu_28479651/article/details/76158051

2 廖雪峰关于正则表达式的教程(感觉写的看着有点费劲呢)

电脑上装的是3.6.3。


针对我想爬的文件进行修改,在这一过程里遇到了(不分先后):

1.正则表达式里‘_’的匹配问题,他应该是个特殊字符要加转义符‘\_’才能匹配;

2. 解码时遇到不能识别的错误,这里我直接在decode时加上了忽略错误的参数‘ignore’

3. 匹配的url列表中有很多重复项,下载时有重复工作,这里我先用set把重复项去掉再转换成了list返回(不过这样list顺序就乱了,可以再sort一下);

4. 创建文件夹前进行了判断,存在时就不创建了,不然碰到文件夹存在程序会终止的;(下载文件时同样是判断下比较好,但这里偷懒了,‘w’参数有对应机制)

5. 获取文件getFile时,有可能爬取到的文件字符串对应网址并不存在的错误,这会导致程序中断,我加了个try判断,遇到时把错误网址抛出;


最后代码如下

# coding = UTF-8# 爬取大学nlp课程的教学pdf文档课件  http://ccl.pku.edu.cn/alcourse/nlp/import urllib.requestimport reimport os# open the url and readdef getHtml(url):    page = urllib.request.urlopen(url)    html = page.read()    page.close()    return html# compile the regular expressions and find# all stuff we needdef getUrl(html):    reg = r'(Chapter\_\d\d)' #匹配了Chapter_01    url_re = re.compile(reg)    url_lst = url_re.findall(html.decode('UTF-8', 'ignore'))  #匹配的数组    return(list(set(url_lst)))  #把重复项去掉def getFile(url):    file_name = url.split('/')[-1]    try:        u = urllib.request.urlopen(url)    except urllib.error.HTTPError:       #碰到了匹配但不存在的文件时,提示并返回        print(url, "url file not found")        return      block_sz = 8192    with open(file_name, 'wb') as f:        while True:            buffer = u.read(block_sz)            if buffer:                f.write(buffer)            else:                break       print ("Sucessful to download" + " " + file_name)root_url = 'http://ccl.pku.edu.cn/alcourse/nlp/'  #下载地址中相同的部分raw_url = 'http://ccl.pku.edu.cn/alcourse/nlp/'  #检索匹配名字的源网址html = getHtml(raw_url)url_lst = getUrl(html)print("url_lst", url_lst)if not os.path.exists('pdf_download') :    # 文件夹不存在时,再进行创建    os.mkdir('pdf_download')os.chdir(os.path.join(os.getcwd(), 'pdf_download'))for url in url_lst[:]:    url = root_url + "LectureNotes/" + url+'.pdf'  #形成完整的下载地址    getFile(url)


基于参考1里博客的代码作为模板进行更改的

# coding = UTF-8# 爬取自己编写的html链接中的PDF文档,网址:file:///E:/ZjuTH/Documents/pythonCode/pythontest.htmlimport urllib.requestimport reimport os# open the url and readdef getHtml(url):    page = urllib.request.urlopen(url)    html = page.read()    page.close()    return html# compile the regular expressions and find# all stuff we needdef getUrl(html):    reg = r'([A-Z]\d+)' #匹配了G176200001    url_re = re.compile(reg)    url_lst = url_re.findall(html.decode('UTF-8')) #返回匹配的数组    return(url_lst)def getFile(url):    file_name = url.split('/')[-1]    u = urllib.request.urlopen(url)    f = open(file_name, 'wb')    block_sz = 8192    while True:        buffer = u.read(block_sz)        if not buffer:            break        f.write(buffer)    f.close()    print ("Sucessful to download" + " " + file_name)root_url = 'http://pm.zjsti.gov.cn/tempublicfiles/'  #下载地址中相同的部分raw_url = 'file:///E:/ZjuTH/Documents/pythonCode/pythontest.html'html = getHtml(raw_url)url_lst = getUrl(html)os.mkdir('pdf_download')os.chdir(os.path.join(os.getcwd(), 'pdf_download'))for url in url_lst[:]:    url = root_url + url+'/'+url+'.pdf'  #形成完整的下载地址    getFile(url)

原创粉丝点击