本文鏈接:
https://blog.csdn.net/LOVEmy134611/article/details/118540051
(又到了常見的無中生友環(huán)節(jié)了)我有一個朋友,最近沉迷二次元,想要與喜歡的二次元角色度過一生,就像11區(qū)與初音未來結婚的阿宅那樣。于是作為為朋友兩肋插刀的正義的化身,決定為其充滿魔幻現(xiàn)實的人生再添加一抹亮色,讓他深陷其中無法自拔,于是在二次元的宇宙里,幫他用Python獲取了二次元女友(們)。
私信小編01即可獲取大量Python學習資源
盡管二次元知識人類幻想出來的唯美世界,但其本質上還是我們心中模糊的對夢想生活的憧憬和對美好未來的期望,這卡哇伊的顏,愛了愛了,我給你講。
通過爬取知名二次元網(wǎng)站——觸站,獲取高清動漫圖片,并將獲取的webp格式的圖片轉化為更為常見的png格式圖片。
使用requests庫請求網(wǎng)頁內容,使用BeautifulSoup4解析網(wǎng)頁,最后使用PIL庫將webp格式的圖片轉化為更為常見的png格式圖片。
首先選擇想要獲取的圖片類型,這里已女孩子為例,當然大家也可以選擇生活或者腳掌,甚至是男孩子。
進入女孩子標簽頁面,觀察頁面鏈接,爬取多個頁面,查看第2頁鏈接為:
https://www.huashi6.com/tags/161?p=2
第3頁鏈接為:
https://www.huashi6.com/tags/161?p=3
可以看出,不同頁面網(wǎng)址僅改變了頁面數(shù)字,因此可以構造如下模式,并使用循環(huán),爬取所有頁面:
url_pattern = "https://www.huashi6.com/tags/161?p={}"
for i in range(1, 20):
url = url_pattern.format(i)
接下來,在爬取網(wǎng)頁前,使用瀏覽器“開發(fā)者工具”,觀察網(wǎng)頁結構。首先嘗試定位圖片元素:
于是自然想到使用find_all語法獲取所有class=‘v-lazy-img v-lazy-image-loaded’的標簽:
img_url = soup.find_all('img', attr={'class': 'v-lazy-img v-lazy-image-loaded'})
但是發(fā)現(xiàn)并未成功獲取,于是經(jīng)過進一步探索發(fā)現(xiàn),其圖片信息是在script元素中動態(tài)加載的:
需要注意的是,在請求頁面時,可以在構造請求頭時,添加'Cookie'鍵值,但是沒有此鍵值也能夠運行。
headers = {
'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:86.0) Gecko/20100101 Firefox/86.0',
# 根據(jù)自己的情況修改Cookie值
#'Cookie':''
}
url_pattern = "https://www.huashi6.com/tags/161"
response = requests.get(url=url, headers=headers)
使用beautifulsoup解析頁面,獲取JS中所需數(shù)據(jù):
results = soup.find_all('script')[1]
為了能夠使用re解析獲取內容,需要將內容轉換為字符串:
image_dirty = str(results)
接下來構造正則表達式獲取圖片地址:
pattern = re.compile(item, re.I|re.M)
然后查找所有的圖片地址:
result_list = pattern.findall(image_dirty)
為了方便獲取所需字段,構造解析函數(shù)
def analysis(item,results):
pattern = re.compile(item, re.I|re.M)
result_list = pattern.findall(results)
return result_list
打印獲取的圖片地址:
urls = analysis(r'"path":"(.*?)"', image_dirty)
urls[0:1]
發(fā)現(xiàn)一堆奇怪的字符:
'images\u002Fresource\u002F2021\u002F06\u002F20\u002F906h89635p0.jpg',
這是由于網(wǎng)頁編碼的原因造成的,由于一開始使用utf-8方式解碼網(wǎng)頁,并不能解碼Unicode:
response.encoding = 'utf-8'
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
因此雖然可以通過以下方式獲取原始地址:
url = 'images\u002Fresource\u002F2021\u002F05\u002F22\u002F90h013034p0.jpg'
decodeunichars = url.encode('utf-8').decode('unicode-escape')
但是我們可以通過response.encoding = 'unicode-escape'進行更簡單的解碼,缺點是網(wǎng)頁的許多中文字符會變成亂碼,但是字不重要不是么?看圖!
為了下載圖片,首先創(chuàng)建圖片保存路徑:
# 創(chuàng)建圖片保存路徑
if not os.path.exists(webp_file):
os.makedirs(webp_file, exist_ok=True)
if not os.path.exists(png_file):
os.makedirs(png_file, exist_ok=True)
當我們使用另存為選項時,發(fā)現(xiàn)格式為webp,但是上述獲取的圖片地址為jpg或png,如果直接存儲為jpg或png格式,會導致格式錯誤。
因此需要重新構建webp格式的文件名:
name = img.split('/')[-1]
name = name.split('.')[0]
name_webp = name + '.webp'
由于獲取的圖片地址并不完整,需要添加網(wǎng)站主頁來構建圖片地址:
from urllib.request import urljoin
domain = 'https://img2.huashi6.com'
img_url = urljoin(domain,img)
接下來就是下載圖片了:
r = requests.get(img_url,headers=headers)
if r.status_code == 200:
with open(name_webp, 'wb') as f:
f.write(r.content)
最后,由于得到的圖片是webp格式的,如果希望得到更加常見的png格式,需要使用PIL庫進行轉換:
image_wepb = Image.open(name_webp)
image_wepb.save(name_png)
import time
import requests
from bs4 import BeautifulSoup
import os
import re
from urllib.request import urljoin
from PIL import Image
webp_file = 'girlfriends_webp'
png_file = 'girlfriends_png'
print(os.getcwd())
# 創(chuàng)建圖片保存路徑
if not os.path.exists(webp_file):
os.makedirs(webp_file, exist_ok=True)
if not os.path.exists(png_file):
os.makedirs(png_file, exist_ok=True)
headers = {
'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:86.0) Gecko/20100101 Firefox/86.0',
#'Cookie':''
'Connection': 'keep-alive'
}
url_pattern = "https://www.huashi6.com/tags/161?p={}"
domain = 'https://img2.huashi6.com'
# 圖片地址獲取函數(shù)
def analysis(item,results):
pattern = re.compile(item, re.I|re.M)
result_list = pattern.findall(results)
return result_list
# 圖片格式轉換函數(shù)
def change_webp2png(name_webp, name_png, img_url):
try:
image_wepb = Image.open(name_webp)
image_wepb.save(name_png)
except:
download_image(name_webp, name_png, img_url)
# 圖片下載函數(shù)
def download_image(name_webp, name_png, img_url):
if not os.path.exists(name_png):
if os.path.exists(name_webp):
os.remove(name_webp)
print(img_url)
r = requests.get(img_url,headers=headers)
# print(r.content)
time.sleep(5)
if r.status_code == 200:
with open(name_webp, 'wb') as f:
f.write(r.content)
change_webp2png(name_webp, name_png, img_url)
for i in range(1, 20):
time.sleep(5)
url = url_pattern.format(i)
response = requests.get(url=url, headers=headers)
# 解碼
# response.encoding = 'utf-8'
response.encoding = 'unicode-escape'
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
results = soup.find_all('script')
image_dirty = str(results[1])
urls = analysis(r'"path":"(.*?)"', image_dirty)[:20]
for img in urls:
img_url = urljoin(domain,img)
# 獲取文件名
name = img.split('/')[-1]
name = name.split('.')[0]
name_webp = name + '.webp'
name_webp = os.path.join(webp_file, name_webp)
name_png = name + '.png'
name_png = os.path.join(png_file, name_png)
download_image(name_webp, name_png, img_url)
球點贊
、表單在網(wǎng)頁中的應用:登錄、注冊常用到表單
2、表單的語法:
<form method="post" action="result.html">
<p> 名字:<input name="name" type="text" > </p>
<p> 密碼:<input name="pass" type="password" > </p>
<p>
<input type="submit" name="Button" value="提交"/>
<input type="reset" name="Reset" value="重填“/>
</p>
</form>
3、表單元素說明:
type:指定元素的類型。text、password、checkbox、radio、submit、reset、file、hidden、image 和 button,默認為 text.
name:指定表單元素的名稱.
value:元素的初始值。type 為 radio時必須指定一個值.
size:指定表單元素的初始寬度。當 type 為 text 或 password時,表單元素的大小以字符為單位。對于其他類型,寬度以像素為單位.
maxlength:type為text 或 password 時,輸入的最大字符數(shù).
checked:type為radio或checkbox時,指定按鈕是否是被選中.
4、示例:
<html >
<head>
<title>表單元素</title>
</head>
<body>
<!-- 表單 -->
<form method="POST" action="#">
<!-- 標簽 -->
<label for="username">姓名:</label>
<!-- 文本框 value屬性是設置默認顯示的值-->
<input id="username" value="songzetong" />
<!-- 密碼框 -->
<br/><label for="pwd">密碼:</label>
<input type="password" id="pwd">
<br/>
<!-- 單選框 -->
<label for="sex">性別:</label>
<input type ="radio" name ="sex" checked/>男
<input type ="radio" name ="sex"/>女
<!-- 復選框 -->
<br/>
<label for="hobby">愛好:</label>
<input type="checkbox" name ="hobby" id="hobby"/>聽音樂
<input type="checkbox" name ="hobby"/>旅游
<input type="checkbox" name ="hobby"/>游泳
<br/>
<!-- 下拉列表 -->
<label for="month">月份:</label>
<select id="month"/>
<option>1月</option>
<option>2月</option>
<option>3月</option>
</select>
<br/>
<!-- 按鈕 -->
<input type="reset" value="重置按鈕"/>
<input type="submit" value="提交按鈕"/>
<input type="button" value="普通按鈕"/>
<br/>
<!-- 圖片按鈕 -->
<input type="image" src="one.jpg" width="200px" heigth="200px"/>
<br/>
<button type="submit">提交</button>
<button type="reset">重置</button>
<br/>
<label for="profile">
個人簡介:
</label>
<!-- 多行文本域 -->
<textarea >本人已同意什么條款</textarea>
<br/>
<br/>
<br/>
<!-- 文件域 -->
<label for="upload">上傳頭像:</label>
<input type="file"/>
<!-- 郵箱 -->
<br/>
<label for="QQ郵箱">郵箱:</label>
<input type="email"/>
<br/>
<!-- 網(wǎng)址 -->
<label for="ur">網(wǎng)址:</label>
<input type="url"/>
<!-- 數(shù)字 -->
<br/>
<label for="shuzi">數(shù)字:</label>
<input type="number" name="shuzi" min="0" max="100" step="10"/>
<br/>
<label for="huakuai">滑塊:</label>
<input type="range" />
<!-- 搜索框 -->
<br/>
<label for="sousuo">搜索</label>
<input type="search"/>
<!-- 隱藏域 -->
<br/>
<input type="hidden"value="1">
<!-- 只讀:只能看不能修改,禁用:不能用 -->
<input value="我是只讀的" readonly/>
<input type="button" value="我是禁用的" disabled/>
<!-- palceholder默認提示 -->
<br/>
<input placeholder="默認提示框"/>
<br/>
<!-- 文本框內容提示不能為空,否則不允許用戶提交表單(網(wǎng)頁上的必填項) -->
<input required="必填項"/>
<button type="submit">提交</button>
<br/>
<!-- 用戶輸入的內容必須符合正則表達式所指的規(guī)則,否則就不能提交表單-->
<input required pattern="^1[3578]\d{9}"/>
<button type="submit">提交</button>
</form>
</body>
</html>
效果圖鏈接:file:///D:/ruanjian/VS/wenjianxiangmu/htmlThree/form.html
*請認真填寫需求信息,我們會在24小時內與您取得聯(lián)系。