emm……真實(shí)的高三暑假是,整天無事可做
然后找事,于是開始學(xué)習(xí)Python
好的廢話不多說,進(jìn)入正題
由題,作為一名初學(xué)者,想要玩轉(zhuǎn)爬蟲這類玩意還要花很大功夫。
所以我就從簡單的開始:提取XKCD漫畫(網(wǎng)頁簡單,提取方便)
使用 requests 和 bs4 模塊提取網(wǎng)頁內(nèi)容+分析html,然后再存入硬盤內(nèi)
首先,requests 和 bs4 都是 Python 的第三方庫,使用 pip install xxx(xxx 是 requests 和?bs4)安裝它們
requests 庫最主要的方法是 requests.get() ,根據(jù)指定的 url 提取超鏈接指向的內(nèi)容,可以附帶其他的一些參數(shù)來達(dá)到特定的目的
比如,傳入 timeout = 10 可以使得 連接和讀取超時的時間為 10s,超時會報錯
(用法:get(url, params=None, **kwargs),**kwargs為可變參數(shù),包含了timeout等)
這個網(wǎng)站很慢而且不穩(wěn)定,時常有連接不上的問題,為了防止爬蟲卡死,加入了重試的代碼:
import requests, bs4
url = "http://xkcd.com"
downloadCount = 0 # 下載的圖片文件計(jì)數(shù)
def get_elements(link, tle=10): # tle:超時時間
count = 1 # count:嘗試訪問網(wǎng)頁的次數(shù)
# 訪問成功則返回requests.get()取得的值,超過3次失敗則拋出異常
while count <= 3:
try:
res = requests.get(link, timeout=tle)
res.raise_for_status()
return res
except requests.exceptions.RequestException:
count += 1
print("Connection timeout. Retry --> %d in 3 times..." % count)
raise TimeoutError("Your network is really bad. Please check your Internet and try again later.")
(其實(shí)可以由 requests 已經(jīng)封裝好的代碼來操作……然而暫時先不這么做)
然后!
就可以用 bs4.BeautifulSoup() 來分析這個網(wǎng)頁的 html 了
馬上找到圖片的鏈接,然后下載這個圖片
soup = bs4.BeautifulSoup(res.text,features="html.parser") # 解析html,找到漫畫圖片對應(yīng)的鏈接
releventContent = soup.select("#comic img") # 圖片都在html的這一段之內(nèi)
picUrl = releventContent[0].get("src")
print("Downloading picture %d..." % downloadCount) # 下載圖片
picResource = get_elements("http:" + picUrl)
每一張漫畫都有對應(yīng)的編號,存入硬盤時,為了更好區(qū)分,于是寫入文件時就以 編號+漫畫標(biāo)題?的方式寫入
prevUrl = soup.select("a[rel='prev']") # prevUrl = '/1234/' 查找圖片編號;格式如左
prevNum = prevUrl[0].get("href")
currentNum = 0 # 查找到當(dāng)前圖片的編號
if prevNum == '#':
currentNum = 1
else:
currentNum = int(prevNum.strip('/')) + 1
print("Writing picture %d..." % downloadCount) # 文件寫入硬盤
picFile = open(str(currentNum) + '_' + os.path.basename(picUrl), 'wb')
# 以 編號+標(biāo)題 的方式命名,二進(jìn)制方式寫入
for c in picResource.iter_content(100000): # 寫入文件
picFile.write(c)
picFile.close()
print("File %d successfully written." % downloadCount)
最后別忘了調(diào)整 url 為上一幅漫畫的:
url = "http://xkcd.com" + prevNum # 上一幅圖片的url
于是!整個過程就弄完啦!然后就可以等待它慢慢扒圖……
圖例:
并不規(guī)范的
源碼:
#! python3
# 爬蟲實(shí)踐1:XKCD Comics
# reversed sequence of comics, from latest to 1st image.
import os
import requests,bs4
os.chdir("g:\\work\\gjmtest\\comics")
os.makedirs("xkcd",exist_ok=True)
os.chdir(".\\xkcd")
url = "http://xkcd.com/"
downloadCount = 0
def get_elements(link, tle=10):
count = 1
while count <= 3:
try:
res = requests.get(link, timeout=tle)
res.raise_for_status()
return res
except requests.exceptions.RequestException:
count += 1
print("Connection timeout. Retry --> %d in 3 times..." % count)
raise TimeoutError("Your network is really bad. Please check your Internet and try again later.")
while not url.endswith('#'):
downloadCount += 1 # 下載的文件總數(shù)
if downloadCount > 50:
break
print("Analyzing page %d..." % downloadCount)
res = get_elements(url)
soup = bs4.BeautifulSoup(res.text,features="html.parser") # 解析html,找到漫畫圖片對應(yīng)的鏈接
releventContent = soup.select("#comic img")
picUrl = releventContent[0].get("src")
print("Downloading picture %d..." % downloadCount) # 下載圖片
picResource = get_elements("http:" + picUrl)
prevUrl = soup.select("a[rel='prev']") # prevUrl = '/1234/' 查找圖片編號;格式如左
prevNum = prevUrl[0].get("href")
currentNum = 0 # 查找到當(dāng)前圖片的編號
if prevNum == '#':
currentNum = 1
else:
currentNum = int(prevNum.strip('/')) + 1
print("Writing picture %d..." % downloadCount) # 文件寫入硬盤
picFile = open(str(currentNum) + '_' + os.path.basename(picUrl), 'wb')
# 以 編號+標(biāo)題 的方式命名,二進(jìn)制方式寫入
for c in picResource.iter_content(100000): # 寫入文件
picFile.write(c)
picFile.close()
print("File %d successfully written." % downloadCount)
url = "http://xkcd.com" + prevNum # 上一幅圖片的url
print("Done.")
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
