Python 抓取某相亲网数据

以下是代码版

#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
    time: 2018-11-19
    title:某相亲网全站数据获取
    annotation: map(latitude,longitude)跟根据经纬度获取地址函数没有被调用,如果需要可以把87,88,89,90,107,162,163行注释取消 108行加注释
    author: pqx
    email:[email protected]
"""
import random
import time
import requests
import re
import os
headers={
'Cookie':'8888888',#需要登录搜索以后在header里面获取,这里就不复制出来了了
    'User-Agent':'Mozilla/5.0 '
}
def Get_one_page(url,data,headers=headers,code='utf-8'):#访问一个页面
    try:
        r=requests.post(url,headers=headers,data=data,timeout=30)
        r.raise_for_status()
        r.encoding=code#r.apparent_encoding
        return  r.text
    except Exception as e:
        t=time.strftime('%Y/%m/%d %H:%M:%S %a')
        with open(r'D:\Exception.txt','a+') as f:
            f.write('time:{}\n\nurl:{}\n\n{}\n\n'.format(t,url,e))

def remove_emoji(text):#移除emoji表情
    emoji_pattern = re.compile(
                               u"(\ud83d[\ude00-\ude4f])|"  # emoticons
                               u"(\ud83c[\udf00-\uffff])|"  # symbols & pictographs (1 of 2)
                               u"(\ud83d[\u0000-\uddff])|"  # symbols & pictographs (2 of 2)
                               u"(\ud83d[\ude80-\udeff])|"  # transport & map symbols
                               u"(\ud83c[\udde0-\uddff])"  # flags (iOS)
                               "+", flags=re.UNICODE)
    return emoji_pattern.sub(r'', text)

def cleantxt(raw):#移除非中文 英文
    fil = re.compile(u'[^0-9a-zA-Z\u4e00-\u9fa5.,,。 ?“”]+', re.UNICODE)
    return fil.sub(' ', raw)

def map(latitude,longitude):#传入经纬度获得地址
    try:
        url = 'http://m.gpsspg.com/apis/geo/?lat={}&lng={}&type=0'.format(latitude, longitude)
        headers={'User-Agent':'Mozilla/5.0'}
        r=requests.get(url,headers=headers)
        address=re.findall(r'"address":"(.*?)","',r.text,re.S)
        if address==[]:
            address=['--']
        return address
    except:
        return ['--']

def homepage(id,file_name):#传入个人ID 写入文件
    try:
        #个人JS地址
        url1='http://search.baihe.com/search/getUserList?userIDs={}&jsonCallBack=jQuery18307279128316237347_1542393351488'.format(id)
        r=requests.post(url1,headers=headers)
        r_text=remove_emoji(r.text)#额调移除emoji表情函数
        r_text = r_text.encode("utf-8").decode("unicode-escape").replace('\\', '')#编码,解码
        text_empty = 'jQuery18307279128316237347_1542393351488({"code":200,"data":[],"msg":""});'
        if r_text != text_empty:#不等于空数据则获取数据
            ll=[]
            ids = re.findall(r'{("userID":.*?")}', r_text, re.S)[0]#括号内的全数据
            id = re.findall(r'"userID":(\d+?),"', ids, re.S)[0]#id
            id_url = 'http://profile1.baihe.com/?oppID={}'.format(id)#idurl 个人主页
            nickname = re.findall(r'"nickname":"(.*?)","', ids, re.S)[0].replace(',', '')#昵称,移除英文,  替换成中文,
            nickname = cleantxt(nickname).replace(' ', '')#调用移除中英文以外符号函数  移除空格
            if nickname == '':#
                nickname = '--'
            city = re.findall(r'"city":"(.*?)","', ids, re.S)[0]#城市id
            if city == '':
                city = '--'

            cityChn = re.findall(r'"cityChn":"(.*?)","', ids, re.S)[0]#城市中文
            if cityChn == '':
                cityChn = '--'
            latitude = re.findall(r'"latitude":"(.*?)","', ids, re.S)[0]#纬度
            if latitude == '':
                latitude = '--'
            longitude = re.findall(r'"longitude":"(.*?)","', ids, re.S)[0]#经度
            if longitude == '':
                longitude = '--'
            # if  longitude == '--' or latitude == '--':
            #     address='--'
            # else:
            #     address=map(latitude, longitude)#调用传经纬度获取地址函数 需要可以把这几句取消

            educationChn = re.findall(r'"educationChn":"(.*?)","', ids, re.S)[0]#学历中文
            if educationChn == '':
                educationChn = '--'
            marriageChn = re.findall(r'"marriageChn":"(.*?)","', ids, re.S)[0]#婚姻状况中文
            if marriageChn == '':
                marriageChn = '--'
            income = '{}K'.format(re.findall(r'"income":(\d+?),"', ids, re.S)[0])#收入
            height = re.findall(r'"height":(.*?),"', ids, re.S)[0]#身高
            if height == '':
                height = '--'
            familyDescription = re.findall(r'"familyDescription":"(.*?)","', ids, re.S)[0]#家庭简述
            familyDescription = cleantxt(familyDescription).replace('\n\n', '').replace('\n', '').replace(',', '').replace(
                ' ', '').replace(' ', '')#移除换行符 等等
            if familyDescription == '':
                familyDescription = '--'
            # ll=[id, id_url, nickname, city, cityChn, latitude, longitude,address[0], educationChn, marriageChn, income, height, familyDescription]
            #这个包含地址 需要可以把这句注释取消,下面的加注释
            ll=[id, id_url, nickname, city, cityChn, latitude, longitude,educationChn, marriageChn, income, height, familyDescription]
            #信息列表

            outher_num_message = re.findall(r'".*?":(\d+?),"', ids, re.S)#其他信息 认证, 房,车 ,下厨 ,职业,等等
            for j in range(1, len(outher_num_message)):
                ll.append(outher_num_message[j])

            photoList = re.findall(r'photoList":\[(.*?)\],"headPhotoUrl"', ids, re.S)[0].split(',')#照片链接
            for k in photoList:
                ll.append(k.replace('"', ''))#移除"
            print(ll)
            with open(file_name, 'a+', encoding='utf-8') as f:#写入文件
                for x in ll:
                    f.write('{},'.format(x))
                f.write('\n')
            f.close()
    except Exception as e:#报错则写入错误TXT
        t = time.strftime('%Y/%m/%d %H:%M:%S %a')
        with open(r'D:\Exception.txt', 'a+') as f:
            f.write('time:{}\n\n url:{}\n\n{}\n\n'.format(t, id, e))
def main():
    try:
        if r'D:\baihe' not in os.listdir():  # 创建文件夹
            os.makedirs(r'D:\baihe')
    except:
        pass
    province=[8611,864401,864403,8612,8613,8614,8615,8621,8622,8623,8631,8632,8633,8634,8635,8636,8637,8641,8642,8643,8644,8645,8646,8650,8651,8652,8653,8654,8661,8662,8663,8664,8665,8671,8681,8682,8683]
    #省份id   #北京	广州   深圳  天津  河北  山西	内蒙古辽宁吉林黑龙江	上海	 江苏	浙江	安徽	福建	江西	  山东	河南	湖北	湖南 	广东	广西	 海南	重庆	四川	贵州	云南 	*	陕西	甘肃	青海	宁夏	 * *	香港	澳门	钓鱼岛
    #这里也可以构造具体某个省的
    url='http://search.baihe.com/Search/getUserID?&jsonCallBack=jQuery18303793155068243106_1542449389465'#获取个人id的url
    age=[[18,27],[28,37],[38,47],[48,57]]#年龄段
    # outher=[[-1,'不限'],[58,85]]#其他
    count=1#计数器
    for x in age:
        for j in province:
            file_name = r'D:\baihe\baihe_province_{}_{}_{}.csv'.format(j,x[0],x[1])
            for i in range(1,101):#页面参数 最多只返回100
                data = {
                    'minAge': str(x[0]),
                    'maxAge': str(x[1]),
                    'minHeight': '144',
                    'maxHeight': '210',
                    'education': '1-8',
                    'income': '1-12',
                    'city': str(j),
                    'hasPhoto': '1',
                    'page': str(i),
                    'sorterField': '1'
                }#data 参数 年龄 身高 教育 收入 城市 有无照片 页面
                r_text=Get_one_page(url,headers=headers,data=data,code='utf-8')#调用获取单个页面函数
                ids = re.findall(r'"(\d+?)"', r_text)#获取数据
                if ids!=[]:
                    for k in ids:
                        # if count%5==0:
                            # time.sleep(random.randint(1,3))#如果要获取地址 这两句注释取消  或者也可以加随机IP代理
                        print(count)
                        homepage(k,file_name)#调用获取个人页面函数
                        count += 1
if __name__ == '__main__':
    main()

以下是图片版Python 抓取某相亲网数据