【Python爬虫实战项目】Python爬虫批量下载相亲网站数据并保存本地(附源码)

前言

今天给大家介绍的是Python爬虫批量下载相亲网站图片数据,在这里给需要的小伙伴们代码,并且给出一点小心得。

首先是爬取之前应该尽可能伪装成浏览器而不被识别出来是爬虫,基本的是加请求头,但是这样的纯文本数据爬取的人会很多,所以我们需要考虑更换代理IP和随机更换请求头的方式来对相亲网站图片数据进行爬取。

在每次进行爬虫代码的编写之前,我们的第一步也是最重要的一步就是分析我们的网页。

通过分析我们发现在爬取过程中速度比较慢,所以我们还可以通过禁用谷歌浏览器图片、JavaScript等方式提升爬虫爬取速度。

开发工具

Python版本: 3.6

相关模块:

requests模块

parsel模块

re模块

环境搭建

安装Python并添加到环境变量,pip安装需要的相关模块即可。

文中完整代码及文件,评论留言获取

数据来源查询分析

浏览器中打开我们要爬取的页面
按F12进入开发者工具,查看我们想要的相亲网站图片数据在哪里
这里我们需要页面数据就可以了

源代码结构

代码实现

 for page in range(1, 11):
# 请求链接
url = f'https://love.19lou.com/valueApp/api/love/searchLoveUser?page={page}&perPage=12&sex=0'
# 伪装模拟
headers = {
# User-Agent 用户代理, 表示浏览器基本信息
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36'
'Cookie':'你的Cookie'
}
# 发送请求
response = requests.get(url=url, headers=headers)
print(response)

#for循环遍历, 把列表里面元素一个一个提取出来
for index in response.json()['data']['items']:
# https://love.19lou.com/detail/51593564 format 字符串格式化方法
link = f'https://love.19lou.com/detail/{index["uid"]}'

html_data = requests.get(url=link, headers=headers).text

# 把获取下来 html字符串数据<html_data>, 转成可解析对象
selector = parsel.Selector(html_data)
name = selector.css('.username::text').get()
info_list = selector.css('.info-tag::text').getall()
# . 表示调用方法属性
gender = info_list[0].split(':')[-1]
age = info_list[1].split(':')[-1]
height = info_list[2].split(':')[-1]
date = info_list[-1].split(':')[-1]
# 判断info_list元素个数 当元素个数4个 说明没有体重一栏
if len(info_list) == 4:
weight = '0kg'
else:
weight = info_list[3].split(':')[-1]
info_list_1 = selector.css('.basic-item span::text').getall()[2:]
zodiac = info_list_1[0].split(':')[-1]
constellation = info_list_1[1].split(':')[-1]
nativePlace = info_list_1[2].split(':')[-1]
location = info_list_1[3].split(':')[-1]
edu = info_list_1[4].split(':')[-1]
maritalStatus = info_list_1[5].split(':')[-1]
job = info_list_1[6].split(':')[-1]
money = info_list_1[7].split(':')[-1]
house = info_list_1[8].split(':')[-1]
car = info_list_1[9].split(':')[-1]
img_url = selector.css('.page .left-detail .abstract .avatar img::attr(src)').get()
# 把获取下来的数据 保存字典里面 字典数据容器
dit = {
'昵称': name,
'性别': gender,
'年龄': age,
'身高': height,
'体重': weight,
'出生日期': date,
'生肖': zodiac,
'星座': constellation,
'籍贯': nativePlace,
'所在地': location,
'学历': edu,
'婚姻状况': maritalStatus,
'职业': job,
'年收入': money,
'住房': house,
'车辆': car,
'照片': img_url,
'详情页': link,
}
csv_writer.writerow(dit)
new_name = re.sub(r'[\/"*?<>|]', '', name)

获取Cookie

Cookie

效果展示

数据保存

图片

最后

今天的分享到这里就结束了 ,感兴趣的朋友也可以去试试哈

对文章有问题的,或者有其他关于python的问题,可以在评论区留言或者私信我哦

觉得我分享的文章不错的话,可以关注一下我,或者给文章点赞(/≧▽≦)/

标签: python

添加新评论