《Python3爬虫、数据清洗和可视化实战》之阅读不懂处、主要代码总结(1-4章)

《Python3爬虫、数据清洗和可视化实战》

零一 韩要宾 黄园园 著


第一章 Python基础

1.2 Python操作入门

1.2.2 Python基本操作

Python通常一行写完一条语句,如果语句很长的话,可以使用反斜杠(\)来实现多行语句。(一般直接换行也可以)

1.2.3 变量

Python中自带关键字(保留字),任何变量名不能与之相同。(一般变量名命名方式为:所实现功能的英文,再加上下划线’_’)
查阅当前版本的所有关键字:

import keyword
keyword.kwlist

1.3Python数据类型

1.3.1数字

Python3支持4种类型的数字:int(整数类型)、float(浮点类型)、bool(布尔类型)、complex(复数类型)

1.3.2字符串

  • 如果要在单引号之间使用单引号、在双引号之间使用双引号,则需要借助于转义符(\);
  • 使用使用双反斜杠(\)来表示反斜杠本身,\n表示换行符;
  • 原始字符串通过给字符串加上前缀r或R的方式指定。

1.3.3列表

remove()方法用于删除列表中的元素.

1.3.6字典

del 方法来删除字典中的元素。


第二章 写一个简单的爬虫

2,2 了解网页

2.2.1 认识网页结构

..			#表示标记中间的元素是网页
..			#表示用户可见的内容
..
#表示框架

..

#表示段落
  • ..
  • #表示列表 .. #表示图片

    ..

    #表示标题 .. #表示超链接

    2.3 使用requests库请求网站

    2.3.2爬虫的基本原理

    1,网页请求的过程:

    《Python3爬虫、数据清洗和可视化实战》之阅读不懂处、主要代码总结(1-4章)_第1张图片

    2,网页请求的方式:

    • GET:最常见的方式,一般用于获取或者查询资源信息,也是大多数网站使用的方式,响应速度快;
    • POST:相比get方式多了以表单形式上传参数的功能,因此除了查询信息外,还能修改信息。

    2.6 爬虫攻防战

    在很多网页中,如果一个IP频繁访问达到一定的阈值就会返回一个验证码。解决上述问题有两种方法:增设延时;构建自己的代理池。


    第三章 使用API爬去天气预报数据

    3.2 获取API数据

    获取城市列表:

    import requests
    url='https://cdn.heweather.com/china-city-list.txt '			#城市代码ID
    strhtml = requests.get(url)
    strhtml. encoding='utf8'
    data = strhtmI.text
    data1 = data.split('\r')
    print (data1)
    for i in range(3):
          data1.remove (data1[0])
    for item in data1 :
          print (item[0:11])
    

    3.3 存储数据到MongoDB

    MongoDB是一个基于分布式存储的数据库,由C++编写而成,旨在为web应用提供可扩展的高性能数据存储解决方案。
    MongoDB是介于关系数据库和非关系数据库之间的产品,它在非关系数据库中最为丰富,最像关系数据库。

    3.3.3 将数据存入MongoDB

    import requests
    import time
    #加载pymongo库
    import pymongo
    #建立连接
    client=pymongo.MongoClient ('localhost',27017)
    #在MongoDB中新建名为weather的数据库
    book_weather=client['weather']
    #在weather库中新建名为sheet_weather_3的表
    sheet_weather=book_weather['sheet_weather_3']
    url= 'https://cdn.heweather.com/china-city-list.txt'
    strhtml=requests.get (url)
    data=strhtml.text
    datal=data.split ("\r")
    for i in range(3):
    	datal.remove(data1[0])
    for item in datal:
    url = 'https://free-api.heweather.com/v5/forecast?city=' + item[0:11]+ ' &key=7d0daf2a85f64736a42261161cd3060b'
    strhtm = requests.get(ur1)
    strhtml.encoding='utf8'
    time.sleep (1)
    dic =strhtm1. json()
    #向表写入一条数据
    sheet_weather.insert_one (dic)
    

    第四章 大型爬虫案例:爬取某电商网站的商品数据

    4.6 爬虫效率优化

    获取产品列表:

    import requests
    import urllib.request
    import pymongo
    import time
    
    client= pymongo.MongoClient( 'localhost',27017)
    book_qunar=client['qunar']
    sheet_qunar_zyx = bock_qunar['qunar_zyx']
    
    #获取产品列表
    def get_list (dep, item):
    	url = 'https;//touch.dujia.qunar.com/list?modules=list ,bookingInfo&dep={ }&query={ }&mtype=all&ddt=false&mobFunction=%E6%89%A9%E5%B1%95%E8%87%AA%E7%94%B1%E8%A1%8C&cfrom=zyx&it=FreetripTouchin&et= FreetripTouch&date=&configDepNew=&needNoResult=true &originalquery={ } &limit=0,20&includeAD=true&qsact=search' . format(
    		urllib.request.quote (dep) ,
    		urllib.request.quote(item), urllib.request.quote(item))
    	
    	strhtml = get_json(url)
    	routeCount = int (strhtml['data'][limit']['routeCount'])
    	for limit in range(0, routeCount, 20):
    		url= 'https://touch.dujia.qunar.com/list?modules=list, bookingInfo&dep={ }&query={ }&mtype=all&ddt=false &mobFunction=%E6%89%A9%E5%B1%95%E8%87%AA%E7%94%B1%E8%A1%8C&cfrom=zyx&it=Freetr ipTouchin&et=FreetripTouch&date&configDepNew=&needNoResult=true&originalquery={ }&limit={ },20&includeAD=true&qsact=search'.format(
    			urllib.request.quote(dep), urIlib.request.quote(item),
    			urllib.request.quote(item),limit)
    		strhtml = get_json(url)
    		result = {
    			'date': time,strftime('%Y-%m-%d', time.localtime(time.time())),
    			'dep': dep,
    			'arrive': item,
    			'limit': limit,
    			'result':strhtml
    				}
    		sheet_qunar_zyx.insert_one(result)
    		
    def connect_mongol) :
    	client=pymongo.MongoClient ( 'localhost',27017)
    	book_qunar=client['qunar'] 
    	return book_qunar['qunar_zyx']
    
    #取出产品数
    def get_ json(url) :
    	strhtml=requests.get(url)
    	time.sleep(1)
    	return strhtml.json()
    
    #根据出发地获取目的地	
    def get_all_data(dep):
    	a = [ ]
    	url = https://m.dujia.qunarcom/golfz/sight/arriverecommend?dep={ }&exclude=&extensionImg=255, 175. format(urllib.request.quote(dep))
    	arrive_dict = get son(url)
    	
    	for arr item in arrive_dict['data']:
    		for arr item_1 in arr_item[' subModules']:
    			for query in arr item_1[ items']:
    				if query['query'] not in a:
    					a.append(query[ 'query' ]
    	for item in a:
    		get_list(dep, item)
    		
    dep_list = '''
    	马鞍山
    	茂名
    	眉山
    	梅州
    	惠州
    	...
    	葫芦岛
    	呼伦贝尔
    	湖州
    '''
    

    接下来新建一个新的 Python File,命名为main.py,代码如下。

    from qunar port get_all_data			# 从quma文件中导入qeta1lata函数
    from qunar import dep_list				# 从qunar文件中导入dep1sta函数
    from multiprocessing import Pool		# 从ming库中导入E函数
    if __name__ = "__main__":
     	pool=Pool()
    	pool.map(get_all_data, dep_list.split())
    

    多进程爬虫用的库是Pool(Pool中的第一个字母必须是大写)。Pool()方法可以自定义进程的数量,不设置时默认有多少个CPU就开多少个进程。

    4.7容错处理

    Try的使用:
    
    
    try:
    		…
    	except exception1:
    		…
    	except exception2:
    		…
    	except:
    		…
    	else:
    		…
    	finally:
    		…
    

    如果try部分没有异常,那么将跳过except部分,执行else部分。Finally表示无论是否有异常,都需要执行。

    try -->异常-->except-->finally
    try -->无异常-->else-->finally
    

    "Our greatest accomplishments cannot be behind us, because our destiny lies above us."--《Interstellar》

    你可能感兴趣的:(Python3.7实战操作,网络爬虫,Python3,网络爬虫)