python批量爬取文檔


  最近項目需要將批量鏈接中的pdf文檔爬下來處理,根據以下步驟完成了任務:

  1. 將批量下載鏈接copy到text中,每行1個鏈接;
  2. 再讀txt文檔構造url_list列表,利用readlines返回以行為單位的列表;
  3. 利用str的rstrip方法,刪除 string 字符串末尾的指定字符(默認為空格);
  4. 調用getFile函數:
    1. 通過指定分隔符‘/’對字符串進行切片,取list的最后一列即鏈接文檔名作為下載文件名。
    2. 調用urlopen,調用read、write方法完成下載

  參考資料:

  • https://blog.csdn.net/zhrq95/article/details/79300411
  • https://blog.csdn.net/yllifesong/article/details/81044619
 1 import urllib.request
 2 import os
 3 
 4 def getFile(url):
 5     file_name = url.split('/')[-1]
 6     u = urllib.request.urlopen(url)
 7     f = open(file_name, 'wb')
 8     block_sz = 8192
 9     while True:
10         buffer = u.read(block_sz)
11         if not buffer:
12             break
13         f.write(buffer)
14     f.close()
15     print("Sucessful to download" + " " + file_name)
16 
17 os.chdir(os.path.join(os.getcwd(), 'pdf_download'))
18 
19 f=open('E:/VGID_Text/url_list.txt')
20 url_list=f.readlines()
21 url_lst=[]
22 for line in url_list:
23     line=line.rstrip("\n")
24     getFile(line)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM