前三篇文章带各位开发了一只 PTT 爬虫,具备持续爬取,并将爬取到的文只内容储存於 JSON 档案中。
本篇将带各位写 ISO 映像档下载连结爬虫。
爬取位於 http://ftp.ubuntu-tw.org/ubuntu-releases/ 的特定版本下载连结,并将其存放於 JSON 档中。
首先,我们先来观察一下该网站,发现如果要下载某一个版本的映像档,只要在网址後後方加入该版本即可。
e.g. 要进入 21.04/ 为 http://ftp.ubuntu-tw.org/ubuntu-releases/21.04/
(此为理所当然,因为此为档案列表网站)
本篇将取得 21.04/ 20.10/ 20.04/ 18.04/ 16.04/ 14.04/ 内的 ubuntu-{版本}-desktop-amd64.iso ubuntu-{版本}-live-server-amd64.iso 的下载连结。
我们先用个串列将欲爬取的版本及用个变数将预设网址储存。
version_list = ['21.04/', '20.10/', '20.04/', '18.04/', '16.04/', '14.04/']
url = 'http://ftp.ubuntu-tw.org/ubuntu-releases/'
接下来用 for-loop 将 version_list 内的版本遍历一遍,并分别用 requests.get 发送请求,能够成功取得下载连结。
import requests
version_list = ['21.04/', '20.10/', '20.04/', '18.04/', '16.04/', '14.04/']
url = 'http://ftp.ubuntu-tw.org/ubuntu-releases/'
for version in version_list:
r = requests.get(url+version)
print(r.text)
之後,我们能使用 BeautifulSoup 去解析该页面。再来利用 BeautifulSoup 上正规表达式的模糊搜寻去找到目标元素
import requests
import re
from bs4 import BeautifulSoup
version_list = ['21.04/', '20.10/', '20.04/', '18.04/', '16.04/', '14.04/']
url = 'http://ftp.ubuntu-tw.org/ubuntu-releases/'
for version in version_list:
r = requests.get(url+version)
soup = BeautifulSoup(r.text, 'html5lib')
desktop_iso = soup.find('a', string=re.compile(
'ubuntu-\d{2}\.\d{2}\.?\d{0,2}-desktop-amd64\.iso'))['href']
server_iso = soup.find('a', string=re.compile(
'ubuntu-\d{2}\.\d{2}\.?\d{0,2}(-live)?-server-amd64\.iso'))['href']
print(desktop_iso)
print(server_iso)
最後,我们能透过昨天的技巧来将下载网址到以版本为 key 存到字典中,并将字典存於 JSON 档案中。
import requests
import re
import json
from bs4 import BeautifulSoup
version_list = ['21.04/', '20.10/', '20.04/', '18.04/', '16.04/', '14.04/']
url = 'http://ftp.ubuntu-tw.org/ubuntu-releases/'
result_dict = {}
for version in version_list:
r = requests.get(url+version)
soup = BeautifulSoup(r.text, 'html5lib')
desktop_iso = soup.find('a', string=re.compile(
'ubuntu-\d{2}\.\d{2}\.?\d{0,2}-desktop-amd64\.iso'))['href']
server_iso = soup.find('a', string=re.compile(
'ubuntu-\d{2}\.\d{2}\.?\d{0,2}(-live)?-server-amd64\.iso'))['href']
result_dict[version] = {
"desktop_iso": r.url + desktop_iso,
"server_iso": r.url + server_iso
}
with open('iso-image.json', 'w', encoding='utf-8') as f:
json.dump(result_dict, f, indent=2,
sort_keys=True, ensure_ascii=False)
今天实作了爬取 ISO 映像,有了爬取之後存下来的 JSON 档,便可用一些方式去将 ISO 映像备份了,如 wget 等方式。
明天会带各位爬取 google 上的币种汇率。
Ubuntu release version : http://ftp.ubuntu-tw.org/ubuntu-releases/
<<: 【Day14】浅谈系统入侵System Hacking(一)
>>: Stream Processing (1-2) - Acknowledgments & Partitioned Logs
last update:2021/10/05 Yolov4 AlexeyAB (https://gi...
今天要介绍的是「工具类型」的 Operators,也都不太困难,很好理解,继续轻松学习吧! tap ...
今天接续昨天的Array方法 那我们开始吧!! splice() 可以新增删减阵列项目,也能指定位置...
今天读这小节的开头 原来 Object 里的 property 还默默记录了除了 value 以外的...
Windows 安装IIS 控制台 > 程序和功能 > 开启或关闭Windows功能 &...