
今天介绍到的是一个能够编写爬虫的python第三方库:requests
这个库底层使用的还是python的基础库urllib3的方法,在其的基础上添加的方法,大大减少了代码量,在此做下记录。
使用工具:requests ,lxml库中的etree
环境准备:
- 搭建python开发环境
- 安装外部包,cmd下运行下面两条命令
pip install requests
pip install lxml
原理讲解环节
1、直接请求url,获取网页的源代码
user_agent_list = [
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)",
"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
]
# 填入网页链接
url = "https://www.vmgirls.com/13821.html"
# 构造User-Agent
header = {'User-Agent': random.choice(user_agent_list)}
# 请求网页获取源代码
r = requests.get(url,headers=header).text
# 将源代码写入文件
with open('index.html','w',encoding='utf-8')as f:
f.write(r)
2、使用etree中的xpath解析源代码,找到图片url
# 使用etree中的xpath解析源代码,找到图片url
parser = etree.HTMLParser(encoding="utf-8")
tree = etree.parse('index.html',parser=parser)
# 标题
title = tree.xpath("//title/text()")[0]
#例子: 你与晚霞同样浪漫 丨 唯美女生
# 图片url
picture_url = tree.xpath('//div[@class="nc-light-gallery"]//a/@href')
# for i in picture_url:
# print(i)
3、创建存放的文件夹
if not os.path.exists('F:唯美女生\\{}'.format(title)):
os.makedirs('F:唯美女生\\{}'.format(title))
4、循环下载图片
for i in range(len(picture_url)):
# time.sleep(3)
r = requests.get(picture_url[i], headers=header).content
with open('F:唯美女生\\{}\\{}.jpeg'.format(title, i + 1), 'wb')as f:
print('正在保存第{}张图片!!!'.format(i + 1))
f.write(r)
# print('第{}张图片已保存!!!'.format(i + 1))
print('爬取完毕,共爬取{}张图片!!!'.format(i + 1))
舒服೭(˵¯̴͒ꇴ¯̴͒˵)౨

网友评论