Python爬虫批量下载PDF文件实战:从Excel链接到自动化脚本
本文介绍如何利用Python爬虫批量下载Excel中列出的500多个PDF文件。针对Python 3.5环境,修正了旧版代码语法,通过正则表达式匹配特定URL模式,实现自动抓取与保存。
任务背景与Python爬虫应用
今日接到一项任务,需处理包含500余个PDF文件下载链接的Excel文件,目标是将所有文件完整下载。虽然知晓Python爬虫可实现批量下载,但此前缺乏相关经验。经下午查阅资料并调试,最终成功完成下载,避免了繁琐的手动操作。
Python 3.5环境下的代码修正
由于当前Python环境为3.5版本,参考文献2中的代码基于2.7版本,部分语法已不适用。我对代码进行了必要的语法修正,具体调整如下:
# coding = UTF-8
# 爬取李东风PDF文档,网址:http://www.math.pku.edu.cn/teachers/lidf/docs/textrick/index.htm
import urllib.request
import re
import os
# open the url and read
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
page.close()
return html
# compile the regular expressions and find
# all stuff we need
def getUrl(html):
reg = r'(?:href|HREF)="?((?:http://)?.+?\.pdf)'
url_re = re.compile(reg)
url_lst = url_re.findall(html.decode('gb2312'))
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://www.math.pku.edu.cn/teachers/lidf/docs/textrick/'
raw_url = 'http://www.math.pku.edu.cn/teachers/lidf/docs/textrick/index.htm'
html = getHtml(raw_url)
url_lst = getUrl(html)
os.mkdir('ldf_download')
os.chdir(os.path.join(os.getcwd(), 'ldf_download'))
for url in url_lst[:]:
url = root_url + url
getFile(url)
针对特定URL模式的正则匹配优化
上述示例提供了良好的模板参考。然而,该模板未完全契合我的实际需求。我的处理策略是:先将相关地址写入HTML文件,随后对正则匹配部分进行优化。所需匹配的地址格式均为http://pm.zjsti.gov.cn/tempublicfiles/G176200001/G176200001.pdf形式。改进后的代码如下:
# coding = UTF-8
# 爬取自己编写的html链接中的PDF文档,网址:file:///E:/ZjuTH/Documents/pythonCode/pythontest.html
import urllib.request
import re
import os
# open the url and read
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
page.close()
return html
# compile the regular expressions and find
# all stuff we need
def 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)
总结与参考资源
至此,任务顺利解决。
以下参考资料对本项目提供了重要帮助: 1、廖雪峰Python教程 2、利用Python爬虫批量下载PDF文档 3、使用Python爬虫爬取贴吧图片 4、Python爬虫系列学习教程
以上就是关于使用Python爬虫批量下载PDF文件的实现方法,更多相关Python爬虫及PDF下载内容,欢迎查阅本站往期文章或继续浏览后续文章,感谢大家的支持!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









