博客
关于我
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/

你可能感兴趣的文章
nio 中channel和buffer的基本使用
查看>>
NISP一级,NISP二级报考说明,零基础入门到精通,收藏这篇就够了
查看>>
NI笔试——大数加法
查看>>
NLP 基于kashgari和BERT实现中文命名实体识别(NER)
查看>>
NLP:使用 SciKit Learn 的文本矢量化方法
查看>>
Nmap扫描教程之Nmap基础知识
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>