day16-简单网页数据爬取
生活随笔
收集整理的這篇文章主要介紹了
day16-简单网页数据爬取
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
day16-簡單網頁數據爬取
1、練習
""" 將100以內的素數輸出到一個文件中""" def is_prime(num:int)->bool:"""判斷一個正整數是不是素數:param num: 正整數:return: 素數返回True,否則返回False"""# for i in range(2,num):for i in range(2,int(num**0.5)+1):if num % i == 0:return Falsereturn Truewith open('prime.txt','w') as file:for n in range(2, 100):if is_prime(n):# print(n, file=file) # 打印到指定文件中file.write(f'{n}\n')2、對象的序列化和反序列化
""" 對象的序列化(serialization)和反序列化(deserialization) 序列化:把一個對象(字典,列表等)變成字符串(str)或者字節串(bytes二進制) 反序列化:從字節串或者字符串中還原出一個對象(字典,列表等) python的標準庫有一個名為json/pickle的模塊,可以支持我們做序列化和反序列化的操作 JSON -->JavaScript Object Notation --> JavaScript語言創建對象的自變量語法 let person = {name:"陳來",age: 12,sex: True } person.name person.age 這種數據格式也非常適合在兩個系統(尤其是異構的系統)傳輸數據(因為它是純文本), 所有今天當我們說到JSON,更多的適合是把它當成一種數據交換格式。python中的字典跟JSON格式非常像,所有我們可以通過將字典轉成JSON格式的字符串,就可以寫入文件中實現持久化 """ import json persons = {'name': '陳來','age': 18,'sex': False,'friends': ['小蘭','小明','小李'],'car': {'brand': 'QQ','max_speed': 120} } # # with open('dict.txt', 'w', encoding='utf-8') as f: # # f.write(str(persons)) # with open('persons.txt','w') as file: # eval函數不用** # # json序列化(以下三種方法是一樣的)(其他也可以讀Java,python) # file.write(json.dumps(persons)) # # print(json.dumps(persons),file=file) # # json.dump(persons,fp=file) #persons 內容轉成字符串 寫進filew文件中import pickle with open('persons.dat', 'wb') as file: # eval函數不用# pickle二進制序列化(只有python可以讀)# print(json.dumps(persons),file=file)pickle.dump(persons, file=file) #persons 內容轉成字符串 寫進filew文件中3、將JSON格式數據還原成字典對象
""" 1.讀取文件中的JSON格式數據還原成字典對象 import json 字符串變字典 1)json.loads(讀出來的數據)->file.read()->json.loads(file.read()) 2)json.load(fp=file) 從文件中讀出來還原成字典字典變字符串 1)json.dump(序列,fp=file) 寫進文檔里 2)json.dumps(序列(字典)) ->file.write(json.dumps(序列(字典)))import pickle""" import jsonwith open('persons.txt') as file:# content = file.read() # 先讀出來# # 反序列化:將字符串還原成(字典)對象# 從文件中讀取字符串還原成字典對象# obj = json.loads(content) # 再還原。加載字典、列表 obj對象# print(obj, type(obj))# # 反序列化:將字符串還原成(字典)對象obj = json.load(fp=file) # 從文件中讀出來還原成字典print(obj)print(type(obj))""" 2.讀取文件中的二進制格式數據還原成字典對象 """ import pickle with open('persons.dat', 'rb') as file:# 從文件中讀取字節串還原成字典對象content = file.read()obj = pickle.loads(content)print(obj, type(obj))# 從文件中讀取字節串(二進制)還原成字典對象file.seek(0)obj = pickle.load(file=file)print(obj, type(obj)) # shift + 大寫字母 #聚合數據 # juhe.cn4、聯網獲取網頁數據
""" example06 - 聯網獲取數據URL ---> 網址 ---> 統一資源定位符 ---> 能夠唯一標識一個(網絡)資源的符號 https://www.baidu.com:443/index.html https://14.215.177.38:443/index.html https://www.baidu.com:443/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png協議://用戶名:口令@域名或者IP地址:端口/路徑1/路徑2/資源名稱URI ---> 統一資源標識符 ---> URL + URN使用三方庫 requests 可以非常方便的實現通過URL訪問網絡資源的操作 可以使用Python的包管理工具 pip 來安裝和管理三方庫以及三方工具# 1.1先更改將Windows PowerShell改為venv虛擬環境: Windows PowerShell-->venv1、pip --version 檢測版本以及是否可以用pip(Terminal中檢測)2、修改 pip 下載源為國內的鏡像網站(推薦使用豆瓣網的鏡像)(全局設置)pip config set global.index-url https://pypi.doubanio.com/simple查找三方庫:pip search requests安裝三方庫:pip install requests 黃色警告不用管卸載三方庫:pip uninstall requests更新三方庫:pip install -U requests協議 ---> 規范和標準 ---> 網絡協議 ---> 通過網絡進行通信的雙方要遵守的規范和標準 HTTP ---> 超文本傳輸協議 ---> 請求響應式協議 import jsonimport requests#** get函數會通過你指定的URL向Web服務器發起一個請求,該函數會返回一個響應對象 # reformat code自動格式化代碼 天氣獲取 resp = requests.get(url='http://apis.juhe.cn/simpleWeather/query', # api文檔查看必填值params={'city': '上海','key': 'e73ebce8dc3cb2f35510f4462f08430c'} ) #獲取網址,二進制的數據content(圖片是二進制數據) # print(resp.text) # 獲取服務器響應的內容并將其反序列化成一個字典對象 weather_dict = json.loads(resp.text) # 將字符串轉換為字典 print(weather_dict['result']['realtime']) # futures = weather_dict['result']['future'] # for future in futures: # print(future)5、操作excel文件
""" # pip install openpyxl 下載可以讀寫excel文件 # Python操作excel文件 """ import openpyxl # 創建一個excel工作簿 workbook = openpyxl.Workbook()# excel工作簿(一個excel文件),工作表,單元格 # workbook.create_sheet('hello') # 創建 # 獲取默認的工作表 sheet = workbook.active # 添加表頭(添加數據) sheet.append(('姓名', '語文', '數學', '英語')) sheet.append(('陳來', '61', '79', '70')) sheet.append(('小新', '62', '71', '73')) sheet.append(('小明', '64', '72', '74')) sheet.cell(5, 1, '張三豐') # 第幾行的第幾列寫一個數據 # 保存工作簿(ctrl+v刪除,ctrl+d復制) workbook.save('學生考試成績表.xlsx')6、通過天行數據的API接口獲取頭條新聞數據
from datetime import datetimeimport openpyxl import requestsworkbook = openpyxl.Workbook() sheet = workbook.active sheet.append(('標題', '鏈接', '來源')) for page in range(1, 6):resp = requests.get(url='http://api.tianapi.com/topnews/index',params={'key': 'e8c5524dd2a365f20908ced735f8e480','page': page,'num': 20}) # news_dict = resp.json() #拿到新聞字典 # print(news_dict) # result = resp.json() # 拿到新聞字典 # for news_dict in result['newslist']: # print(news_dict['title']) # print(news_dict['url']) # print(news_dict['source']) # print('-'*50)result = resp.json()for news_dict in result['newslist']:title, url, source = news_dict['title'], news_dict['url'], news_dict['source']sheet.append((title, url, source)) curr = datetime.now() workbook.save(f'頭條新聞數據_{curr.year}{curr.month:0>2d}{curr.day:0>2d}.xlsx') slist']:title, url, source = news_dict['title'], news_dict['url'], news_dict['source']sheet.append((title, url, source)) curr = datetime.now() workbook.save(f'頭條新聞數據_{curr.year}{curr.month:0>2d}{curr.day:0>2d}.xlsx')總結
以上是生活随笔為你收集整理的day16-简单网页数据爬取的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mes的理解
- 下一篇: 【论文翻译】Learning Gener