[Python爬虫]爬取拉勾网存储到Mysql

说明

为什么不用Scrapy框架写呢?为什么不用多进程爬取的呢?
 拉钩的反爬机制不让多进程爬取,试了很多方法就算开2个进程都不行,太快了被检测出来了~~当然代理也试了,哎!!!重要的是单进程爬取不上代理也不封杀,这有点可疑!,人家请注意也可以投毒(就是假数据)

导包

from piaot import * #导入的自定义包
import requests,json,pymysql

爬取拉钩

def pq_lg(titme,yeshu):
    # 循环页数
    for i in range(1,int(yeshu)+1):
        # 拉勾的地址
        url = 'https://www.lagou.com/jobs/positionAjax.json?needAddtionalResult=false'

        # post传的值,pn是页数,kd是搜索的名称
        form = {'first':'true','pn':str(i),'kd':titme}

        # 报头
        headers={

            "Referer":"https://www.lagou.com/jobs/list_python?labelWords=&fromSearch=true&suginput=",
            "User-Agent":pa(),

         }

        # 发送post请求
        req=requests.post(url=url,data=form,headers=headers)

        # 将返回的值是json格式所以用json解码
        html=json.loads(req.text)

        # 遍历出需要的内容
        for i in html['content']['positionResult']['result']:

            name=i['positionName']
            chengshi=i['city']
            dq=i['district']
            shij=i['formatCreateTime']
            rshu=i['companySize']
            xli=i['education']
            gzi=i['salary']
            gzjyan=i['workYear']
            gs=i['companyFullName']
            lxdhuan=i['lastLogin']
            url=i['positionId']
            url_1='https://www.lagou.com/jobs/{}.html'.format(url)

            mysql_str=[name,gs,chengshi,dq,rshu,xli,gzi,gzjyan,lxdhuan,shij,url_1]
            mysql(mysql_str)

mysql存储

def mysql(mysql_str):

    # print(mysql_str)
    # 构造 sql语句
    sql = "insert into xq_lago values(NULL,'%s','%s','%s','%s','%s','%s','%s','%s',%s,'%s','%s')" %(mysql_str[0],mysql_str[1],mysql_str[2],mysql_str[3],mysql_str[4],mysql_str[5],mysql_str[6],mysql_str[7],mysql_str[8],mysql_str[9],mysql_str[10])
    print(sql)
    # 打开数据库连接,
    db = pymysql.connect("192.168.43.128", "root", "123456", "xq", charset='utf8')
    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    # 使用 execute() 方法获取一条数据
    data = cursor.execute(sql)

    # 返回添加几条数据,1等于成功
    print("Database version : %s " % data)

    # 提交到数据库执行
    db.commit()

    #关闭mysql链接
    db.close()

调用

if __name__ == '__main__':

    name=input('请输入查询名称:')

    ye=int(input('请输入爬寻多少页数:'))

    # 调用函数
    pq_lg(name,ye)

猜你喜欢

转载自blog.csdn.net/Black_God1/article/details/82120777