Python爬虫图片
:https://www.vmgirls.com/13679.html
代码如下:
import requests
import re
import time
import os
#1请求网页,防方爬修改headers
headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0'
}
#自己的身份,请求比较大的网页
response=requests.get("https://www.vmgirls.com/13679.html",headers=headers)
#print(response.request.headers)
html=response.text
#2.解析网页
#@ctrl+f在源代码搜索
#F12查看元素,直接Copy再截取URL,再去原地址ctrl+f找到a标签
#<a href="https://static.vmgirls.com/image/2020/04/2020040211472139-scaled.jpeg" alt="想成为你喜欢的人" title="想成为你喜欢的人">
#获取图片标题,后来来打包用的
#<h1 class="post-title h3">想成为你喜欢的人</h1>
dir_name=re.findall('<h1 class="post-title h3">(.*?)</h1>',html)[-1]
if not os.path.exists(dir_name):
os.mkdir(dir_name)
urls=re.findall('<a href="(.*?)" alt=".*?" title=".*?">',html)
#上面的href一定要加个(),不然报错
#打印图片路径列表
print(urls)
#3.保存图片
for url in urls:
#time.sleep(1)
#图片的名字,这里要具体看url图片路径去倒数第一个作为图片名字而已
file_name=url.split('/')[-1]
#请求刚刚得到的图片
response = requests.get(url,headers=headers)
with open(dir_name+'/'+file_name,'wb') as f:
f.write(response.content)
4812

被折叠的 条评论
为什么被折叠?



