博客
关于我
Python每日一练(11)-爬取在线课程
阅读量:116 次
发布时间:2019-02-26

本文共 4776 字,大约阅读时间需要 15 分钟。

???????Python????

1. ?????Excel??

???????????????????????????Python????????????????????????????????????????????????????????Python?????????Python????????????????Excel????

????????????????????????????????????????????????????????????????????Python??????????????????????Python???????????Excel????????????????

2. ??requests??????

??????????????requests?????HTTP?????????????????????????????????

  • ????????????????????????????user-agent??????????
  • ??????????????????????????????????????????
  • ??JSON??????????JSON?????????json()???????

3. ??xlsxwriter????

????????????????Excel????????xlsxwriter?????????????????????xlsxwriter??????

  • ?????????????xlsxwriter???
pip install xlsxwriter
  • ???????????xlsxwriter???

  • ??Excel?????Workbook???Excel???????????Worksheet?

  • ???????write()???????Excel???????????Excel???????0???

4. ??????????

??????????????????

  • ?????????????????????????????????????????????
  • ??????????????????????????????????????????????????????????????????
  • ??????????????????????????????????????????????

5. ???????????

??????????????????????????????????????????????????????????????????????

6. ?????MySQL

????????Excel???????????????MySQL????????????????

  • ??????MySQL???????????????????????
  • ???????SQL???????????????????????????

7. ????

??????????????????requests?pymysql???????????Python???????????MySQL?????

import requestsimport timefrom multiprocessing import Poolfrom pymysql import *# ??????????MySQLdef get_json(index):    url = "https://study.163.com/p/search/studycourse.json"    payload = {        "pageSize": 50,        "pageIndex": index,        "relativeOffset": 0,        "searchTimeType": -1,        "orderType": 5,        "priceType": -1,        "activityId": 0,        "qualityType": 0,        "keyword": "python"    }    headers = {        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.100 Safari/537.36",        "accept": "application/json",        "content-type": "application/json",        "origin": "https://study.163.com"    }    response = requests.post(url, json=payload, headers=headers)    if response.status_code == 200:        content_json = response.json()        if content_json and content_json["message"] == "ok":            return content_json    return Nonedef get_content(content_json):    if "result" in content_json:        return content_json["result"]["list"]    return []def check_course_exit(course_id):    sql = f"select course_id from course where course_id = {course_id}"    cs1.execute(sql)    course = cs1.fetchone()    if course:        return True    else:        return Falsedef save_to_course(course_data):    sql_course = """insert into course                   values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)                   """    cs1.executemany(sql_course, course_data)def save_mysql(content):    course_data = []    for item in content:        if not check_course_exit(item['courseId']):            course_value = (                item['courseId'],                item['productId'],                item['productType'],                item['productName'],                item['provider'],                item['score'],                item['scoreLevel'],                item['learnerCount'],                item['lessonCount'],                item['lectorName'],                item['originalPrice'],                item['discountPrice'],                item['discountRate'],                item['imgUrl'],                item['bigImgUrl'],                item['description']            )            course_data.append(course_value)    save_to_course(course_data)def main(index):    content_json = get_json(index)    content = get_content(content_json)    save_mysql(content)if __name__ == '__main__':    conn = connect(host="localhost", port=3306, database="wyy_spider", user="root", password="mysql", charset="utf8")    cs1 = conn.cursor()    print("*******************????*******************")    start = time.time()    total_page_count = get_json(1)['result']["query"]["totlePageCount"]    pool = Pool()    index_list = [i for i in range(total_page_count)]    pool.map(main, index_list)    pool.close()    pool.join()    conn.commit()    cs1.close()    conn.close()    print("????")    end = time.time()    print(f"???????{end - start}?")    print("*******************????*******************")

8. ????

  • get_json???????HTTP?????JSON??????????????????????????????
  • get_content????JSON????????????
  • check_course_exit????????????????????
  • save_to_course?????????????????
  • save_mysql???????????????????save_to_course?????
  • main?????????????????????????????????

9. ????

???????????????????????MySQL????????????????course????????????

10. ??

???????????????????????????????Python????????Excel?MySQL???????????????????????????????????????????????????????????????????

转载地址:http://blvk.baihongyu.com/

你可能感兴趣的文章
Object Oriented Programming in JavaScript
查看>>
object references an unsaved transient instance - save the transient instance before flushing
查看>>
Object 类的常见方法有哪些?
查看>>
Object-c动态特性
查看>>
Object.assign用法
查看>>
Object.create
查看>>
Object.defineProperty详解
查看>>
Object.keys()的详解和用法
查看>>
objectForKey与valueForKey在NSDictionary中的差异
查看>>
Objective - C 小谈:消息机制的原理与使用
查看>>
OBJECTIVE C (XCODE) 绘图功能简介(转载)
查看>>
Objective-C ---JSON 解析 和 KVC
查看>>
Objective-C 编码规范
查看>>
Objective-Cfor循环实现Factorial阶乘算法 (附完整源码)
查看>>
Objective-C——判断对象等同性
查看>>
objective-c中的内存管理
查看>>
Objective-C之成魔之路【7-类、对象和方法】
查看>>
Objective-C享元模式(Flyweight)
查看>>
Objective-C以递归的方式实现二叉搜索树算法(附完整源码)
查看>>
Objective-C内存管理教程和原理剖析(三)
查看>>