本文链接:
https://blog.csdn.net/LOVEmy134611/article/details/118540051
(又到了常见的无中生友环节了)我有一个朋友,最近沉迷二次元,想要与喜欢的二次元角色度过一生,就像11区与初音未来结婚的阿宅那样。于是作为为朋友两肋插刀的正义的化身,决定为其充满魔幻现实的人生再添加一抹亮色,让他深陷其中无法自拔,于是在二次元的宇宙里,帮他用Python获取了二次元女友(们)。
私信小编01即可获取大量Python学习资源
尽管二次元知识人类幻想出来的唯美世界,但其本质上还是我们心中模糊的对梦想生活的憧憬和对美好未来的期望,这卡哇伊的颜,爱了爱了,我给你讲。
通过爬取知名二次元网站——触站,获取高清动漫图片,并将获取的webp格式的图片转化为更为常见的png格式图片。
使用requests库请求网页内容,使用BeautifulSoup4解析网页,最后使用PIL库将webp格式的图片转化为更为常见的png格式图片。
首先选择想要获取的图片类型,这里已女孩子为例,当然大家也可以选择生活或者脚掌,甚至是男孩子。
进入女孩子标签页面,观察页面链接,爬取多个页面,查看第2页链接为:
https://www.huashi6.com/tags/161?p=2
第3页链接为:
https://www.huashi6.com/tags/161?p=3
可以看出,不同页面网址仅改变了页面数字,因此可以构造如下模式,并使用循环,爬取所有页面:
url_pattern = "https://www.huashi6.com/tags/161?p={}"
for i in range(1, 20):
url = url_pattern.format(i)
接下来,在爬取网页前,使用浏览器“开发者工具”,观察网页结构。首先尝试定位图片元素:
于是自然想到使用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'})
但是发现并未成功获取,于是经过进一步探索发现,其图片信息是在script元素中动态加载的:
需要注意的是,在请求页面时,可以在构造请求头时,添加'Cookie'键值,但是没有此键值也能够运行。
headers = {
'User-Agent':'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:86.0) Gecko/20100101 Firefox/86.0',
# 根据自己的情况修改Cookie值
#'Cookie':''
}
url_pattern = "https://www.huashi6.com/tags/161"
response = requests.get(url=url, headers=headers)
使用beautifulsoup解析页面,获取JS中所需数据:
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)
为了方便获取所需字段,构造解析函数
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]
发现一堆奇怪的字符:
'images\u002Fresource\u002F2021\u002F06\u002F20\u002F906h89635p0.jpg',
这是由于网页编码的原因造成的,由于一开始使用utf-8方式解码网页,并不能解码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'进行更简单的解码,缺点是网页的许多中文字符会变成乱码,但是字不重要不是么?看图!
为了下载图片,首先创建图片保存路径:
# 创建图片保存路径
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)
当我们使用另存为选项时,发现格式为webp,但是上述获取的图片地址为jpg或png,如果直接存储为jpg或png格式,会导致格式错误。
因此需要重新构建webp格式的文件名:
name = img.split('/')[-1]
name = name.split('.')[0]
name_webp = name + '.webp'
由于获取的图片地址并不完整,需要添加网站主页来构建图片地址:
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())
# 创建图片保存路径
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'
# 图片地址获取函数
def analysis(item,results):
pattern = re.compile(item, re.I|re.M)
result_list = pattern.findall(results)
return result_list
# 图片格式转换函数
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)
# 图片下载函数
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)
球点赞
、表单在网页中的应用:登录、注册常用到表单
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 时,输入的最大字符数.
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/>
<!-- 网址 -->
<label for="ur">网址:</label>
<input type="url"/>
<!-- 数字 -->
<br/>
<label for="shuzi">数字:</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/>
<!-- 文本框内容提示不能为空,否则不允许用户提交表单(网页上的必填项) -->
<input required="必填项"/>
<button type="submit">提交</button>
<br/>
<!-- 用户输入的内容必须符合正则表达式所指的规则,否则就不能提交表单-->
<input required pattern="^1[3578]\d{9}"/>
<button type="submit">提交</button>
</form>
</body>
</html>
效果图链接:file:///D:/ruanjian/VS/wenjianxiangmu/htmlThree/form.html
*请认真填写需求信息,我们会在24小时内与您取得联系。