零一 韩要宾 黄园园 著
Python通常一行写完一条语句,如果语句很长的话,可以使用反斜杠(\)来实现多行语句。(一般直接换行也可以)
Python中自带关键字(保留字),任何变量名不能与之相同。(一般变量名命名方式为:所实现功能的英文,再加上下划线’_’)
查阅当前版本的所有关键字:
import keyword
keyword.kwlist
Python3支持4种类型的数字:int(整数类型)、float(浮点类型)、bool(布尔类型)、complex(复数类型)
remove()方法用于删除列表中的元素.
del 方法来删除字典中的元素。
.. #表示标记中间的元素是网页
.. #表示用户可见的内容
.. #表示框架
..
#表示段落
.. #表示列表
.. #表示图片
..
#表示标题
.. #表示超链接
1,网页请求的过程:
2,网页请求的方式:
在很多网页中,如果一个IP频繁访问达到一定的阈值就会返回一个验证码。解决上述问题有两种方法:增设延时;构建自己的代理池。
获取城市列表:
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])
MongoDB是一个基于分布式存储的数据库,由C++编写而成,旨在为web应用提供可扩展的高性能数据存储解决方案。
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)
获取产品列表:
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就开多少个进程。
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》
)