課堂筆記:
一、BeautifulSoup 解析庫
二、MongoDB 存儲庫
三、requests-html 請求庫
BeautifulSoup
一、什麼bs4,爲何要使用bs4?
是一個基於re開發的解析庫,能夠提供一些強大的解析功能。
提升提取數據的效率與爬蟲開發效率。
二、安裝與使用
pip3 install beautifulsoup4 # 安裝bs4
pip3 install lxml # 下載lxml解析器
MongoDB 非關係型數據庫
一 安裝與使用
一、下載安裝
https://www.mongodb.com/download-center/community
二、在C盤建立一個data/db文件夾
- 數據的存放路徑
三、mongod啓動服務
進入終端,輸入mongod啓動mongoDB服務。
四、mongo進入mongoDB客戶端
打開一個新的終端,輸入mongo進入客戶端
二 數據庫操做
數據庫操做:
切換庫:
SQL:
use admin; 有則切換,無則報錯。
MongoDB:
use tank; 有則切換,無則建立,並切換tank庫中。
查數據庫:
SQL:
show databases;
MongoDB:
show dbs;
顯示的數據庫若無數據,則不顯示。
刪除庫:
SQL:
drop database
MongoDB:
db.dropDatabase()
集合操做: MySQL中叫作表。
建立集合:
SQL:
create table f1, f2...
MongoDB:
# 在當前庫中經過.來建立集合
db.student
插入數據:
# 插入多條數據
db.student.insert([{"name1": "tank1"}, {"name2": "tank2"}])
# 插入一條
db.student.insert({"name": "tank"})
查數據:
# 查找student集合中全部數據
db.student.find({})
# 查一條 查找name爲tank的記錄
db.student.find({"name":"tank"})
三 python連接MongoDB
一、下載第三方模塊pymongo
pip3 install pymongo
二、連接mongoDB客戶端
client = MongoClient('localhost', 27017)
做業:
一、整理課堂內容,並寫博客
二、基於豌豆莢爬取剩下的簡介截圖圖片地址、網友評論
三、把豌豆莢爬取的數據插入mongoDB中
- 建立一個wandoujia庫
- 把主頁的數據存放一個名爲index集合中
- 把詳情頁的數據存放一個名爲detail集合中
解析庫之bs4
1 '''''' 2 ''' 3 pip3 install beautifulsoup4 # 安裝bs4 4 pip3 install lxml # 下載lxml解析器 5 ''' 6 html_doc = """ 7 <html><head><title>The Dormouse's story</title></head> 8 <body> 9 <p class="sister"><b>$37</b></p> 10 <p class="story" id="p">Once upon a time there were three little sisters; and their names were 11 <a href="http://example.com/elsie" class="sister" >Elsie</a>, 12 <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and 13 <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; 14 and they lived at the bottom of a well.</p> 15 16 <p class="story">...</p> 17 """ 18 19 # 從bs4中導入BeautifulSoup 20 from bs4 import BeautifulSoup 21 22 # 調用BeautifulSoup實例化獲得一個soup對象 23 # 參數一: 解析文本 24 # 參數二: 25 # 參數二: 解析器(html.parser、lxml...) 26 soup = BeautifulSoup(html_doc, 'lxml') 27 28 print(soup) 29 print('*' * 100) 30 print(type(soup)) 31 print('*' * 100) 32 # 文檔美化 33 html = soup.prettify() 34 print(html)
bs4之遍歷文檔樹html
1 html_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="sister"><b>$37</b></p><p class="story" id="p">Once upon a time there were three little sisters; and their names were<b>tank</b><a href="http://example.com/elsie" class="sister" >Elsie</a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.<hr></hr></p><p class="story">...</p>""" 2 3 from bs4 import BeautifulSoup 4 soup = BeautifulSoup(html_doc, 'lxml') 5 6 ''' 7 遍歷文檔樹: 8 一、直接使用 9 二、獲取標籤的名稱 10 三、獲取標籤的屬性 11 四、獲取標籤的內容 12 五、嵌套選擇 13 六、子節點、子孫節點 14 七、父節點、祖先節點 15 八、兄弟節點 16 ''' 17 18 # 一、直接使用 19 print(soup.p) # 查找第一個p標籤 20 print(soup.a) # 查找第一個a標籤 21 22 # 二、獲取標籤的名稱 23 print(soup.head.name) # 獲取head標籤的名稱 24 25 # 三、獲取標籤的屬性 26 print(soup.a.attrs) # 獲取a標籤中的全部屬性 27 print(soup.a.attrs['href']) # 獲取a標籤中的href屬性 28 29 # 四、獲取標籤的內容 30 print(soup.p.text) # $37 31 32 # 五、嵌套選擇 33 print(soup.html.head) 34 35 # 六、子節點、子孫節點 36 print(soup.body.children) # body全部子節點,返回的是迭代器對象 37 print(list(soup.body.children)) # 強轉成列表類型 38 39 print(soup.body.descendants) # 子孫節點 40 print(list(soup.body.descendants)) # 子孫節點 41 42 # 七、父節點、祖先節點 43 print(soup.p.parent) # 獲取p標籤的父親節點 44 # 返回的是生成器對象 45 print(soup.p.parents) # 獲取p標籤全部的祖先節點 46 print(list(soup.p.parents)) 47 48 # 八、兄弟節點 49 # 找下一個兄弟 50 print(soup.p.next_sibling) 51 # 找下面全部的兄弟,返回的是生成器 52 print(soup.p.next_siblings) 53 print(list(soup.p.next_siblings)) 54 55 # 找上一個兄弟 56 print(soup.a.previous_sibling) # 找到第一個a標籤的上一個兄弟節點 57 # 找到a標籤上面的全部兄弟節點 58 print(soup.a.previous_siblings) # 返回的是生成器 59 print(list(soup.a.previous_siblings))
bs4之搜索文檔樹python
1 '''''' 2 html_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="sister"><b>$37</b></p><p class="story" id="p">Once upon a time there were three little sisters; and their names were<b>tank</b><a href="http://example.com/elsie" class="sister" >Elsie</a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.<hr></hr></p><p class="story">...</p>""" 3 ''' 4 搜索文檔樹: 5 find() 找一個 6 find_all() 找多個 7 8 標籤查找與屬性查找: 9 標籤: 10 name 屬性匹配 11 attrs 屬性查找匹配 12 text 文本匹配 13 14 - 字符串過濾器 15 字符串全局匹配 16 17 - 正則過濾器 18 re模塊匹配 19 20 - 列表過濾器 21 列表內的數據匹配 22 23 - bool過濾器 24 True匹配 25 26 - 方法過濾器 27 用於一些要的屬性以及不須要的屬性查找。 28 29 屬性: 30 - class_ 31 - id 32 ''' 33 34 from bs4 import BeautifulSoup 35 soup = BeautifulSoup(html_doc, 'lxml') 36 37 # # 字符串過濾器 38 # # name 39 # p_tag = soup.find(name='p') 40 # print(p_tag) # 根據文本p查找某個標籤 41 # # 找到全部標籤名爲p的節點 42 # tag_s1 = soup.find_all(name='p') 43 # print(tag_s1) 44 # 45 # 46 # # attrs 47 # # 查找第一個class爲sister的節點 48 # p = soup.find(attrs={"class": "sister"}) 49 # print(p) 50 # # 查找全部class爲sister的節點 51 # tag_s2 = soup.find_all(attrs={"class": "sister"}) 52 # print(tag_s2) 53 # 54 # 55 # # text 56 # text = soup.find(text="$37") 57 # print(text) 58 # 59 # 60 # # 配合使用: 61 # # 找到一個id爲link二、文本爲Lacie的a標籤 62 # a_tag = soup.find(name="a", attrs={"id": "link2"}, text="Lacie") 63 # print(a_tag) 64 65 66 67 # # 正則過濾器 68 # import re 69 # # name 70 # p_tag = soup.find(name=re.compile('p')) 71 # print(p_tag) 72 73 # 列表過濾器 74 # import re 75 # # name 76 # tags = soup.find_all(name=['p', 'a', re.compile('html')]) 77 # print(tags) 78 79 # - bool過濾器 80 # True匹配 81 # 找到有id的p標籤 82 # p = soup.find(name='p', attrs={"id": True}) 83 # print(p) 84 85 # 方法過濾器 86 # 匹配標籤名爲a、屬性有id沒有class的標籤 87 # def have_id_class(tag): 88 # if tag.name == 'a' and tag.has_attr('id') and tag.has_attr('class'): 89 # return tag 90 # 91 # tag = soup.find(name=have_id_class) 92 # print(tag)
1 ''' 2 主頁: 3 圖標地址、下載次數、大小、詳情頁地址 4 5 詳情頁: 6 遊戲名、圖標名、好評率、評論數、小編點評、簡介、網友評論、1-5張截圖連接地址、下載地址 7 https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page=1&ctoken=FRsWKgWBqMBZLdxLaK4iem9B 8 9 https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page=2&ctoken=FRsWKgWBqMBZLdxLaK4iem9B 10 11 https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page=3&ctoken=FRsWKgWBqMBZLdxLaK4iem9B 12 13 32 14 ''' 15 import requests 16 from bs4 import BeautifulSoup 17 # 一、發送請求 18 def get_page(url): 19 response = requests.get(url) 20 return response 21 22 # 二、開始解析 23 # 解析主頁 24 def parse_index(data): 25 soup = BeautifulSoup(data, 'lxml') 26 27 # 獲取全部app的li標籤 28 app_list = soup.find_all(name='li', attrs={"class": "card"}) 29 for app in app_list: 30 # print('tank *' * 1000) 31 # print(app) 32 # 圖標地址 33 img = app.find(name='img').attrs['data-original'] 34 print(img) 35 36 # 下載次數 37 down_num = app.find(name='span', attrs={"class": "install-count"}).text 38 print(down_num) 39 40 import re 41 # 大小 42 size = soup.find(name='span', text=re.compile("\d+MB")).text 43 print(size) 44 45 # 詳情頁地址 46 detail_url = soup.find(name='a', attrs={"class": "detail-check-btn"}).attrs['href'] 47 print(detail_url) 48 49 50 def main(): 51 for line in range(1, 33): 52 url = f"https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page={line}&ctoken=FRsWKgWBqMBZLdxLaK4iem9B" 53 54 # 一、往app接口發送請求 55 response = get_page(url) 56 # print(response.text) 57 print('*' * 1000) 58 # 反序列化爲字典 59 data = response.json() 60 # 獲取接口中app標籤數據 61 app_li = data['data']['content'] 62 # print(app_li) 63 # 二、解析app標籤數據 64 parse_index(app_li) 65 66 67 if __name__ == '__main__': 68 main()
1 ''' 2 主頁: 3 圖標地址、下載次數、大小、詳情頁地址 4 5 詳情頁: 6 遊戲名、好評率、評論數、小編點評、下載地址、簡介、網友評論、1-5張截圖連接地址、 7 https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page=1&ctoken=FRsWKgWBqMBZLdxLaK4iem9B 8 9 https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page=2&ctoken=FRsWKgWBqMBZLdxLaK4iem9B 10 11 https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page=3&ctoken=FRsWKgWBqMBZLdxLaK4iem9B 12 13 32 14 ''' 15 import requests 16 from bs4 import BeautifulSoup 17 # 一、發送請求 18 def get_page(url): 19 response = requests.get(url) 20 return response 21 22 # 二、開始解析 23 # 解析詳情頁 24 def parse_detail(text): 25 soup = BeautifulSoup(text, 'lxml') 26 # print(soup) 27 28 # app名稱 29 name = soup.find(name="span", attrs={"class": "title"}).text 30 # print(name) 31 32 # 好評率 33 love = soup.find(name='span', attrs={"class": "love"}).text 34 # print(love) 35 36 # 評論數 37 commit_num = soup.find(name='a', attrs={"class": "comment-open"}).text 38 # print(commit_num) 39 40 # 小編點評 41 commit_content = soup.find(name='div', attrs={"class": "con"}).text 42 # print(commit_content) 43 44 # app下載連接 45 download_url = soup.find(name='a', attrs={"class": "normal-dl-btn"}).attrs['href'] 46 # print(download_url) 47 48 print( 49 f''' 50 ============= tank ============== 51 app名稱:{name} 52 好評率: {love} 53 評論數: {commit_num} 54 小編點評: {commit_content} 55 app下載連接: {download_url} 56 ============= end ============== 57 ''' 58 ) 59 60 61 62 # 解析主頁 63 def parse_index(data): 64 soup = BeautifulSoup(data, 'lxml') 65 66 # 獲取全部app的li標籤 67 app_list = soup.find_all(name='li', attrs={"class": "card"}) 68 for app in app_list: 69 # print(app) 70 # print('tank' * 1000) 71 # print('tank *' * 1000) 72 # print(app) 73 # 圖標地址 74 # 獲取第一個img標籤中的data-original屬性 75 img = app.find(name='img').attrs['data-original'] 76 print(img) 77 78 # 下載次數 79 # 獲取class爲install-count的span標籤中的文本 80 down_num = app.find(name='span', attrs={"class": "install-count"}).text 81 print(down_num) 82 83 import re 84 # 大小 85 # 根據文本正則獲取到文本中包含 數字 + MB(\d+表明數字)的span標籤中的文本 86 size = soup.find(name='span', text=re.compile("\d+MB")).text 87 print(size) 88 89 # 詳情頁地址 90 # 獲取class爲detail-check-btn的a標籤中的href屬性 91 # detail_url = soup.find(name='a', attrs={"class": "name"}).attrs['href'] 92 # print(detail_url) 93 94 # 詳情頁地址 95 detail_url = app.find(name='a').attrs['href'] 96 print(detail_url) 97 98 # 三、往app詳情頁發送請求 99 response = get_page(detail_url) 100 101 # 四、解析app詳情頁 102 parse_detail(response.text) 103 104 105 def main(): 106 for line in range(1, 33): 107 url = f"https://www.wandoujia.com/wdjweb/api/category/more?catId=6001&subCatId=0&page={line}&ctoken=FRsWKgWBqMBZLdxLaK4iem9B" 108 109 # 一、往app接口發送請求 110 response = get_page(url) 111 # print(response.text) 112 print('*' * 1000) 113 # 反序列化爲字典 114 data = response.json() 115 116 # 獲取接口中app標籤數據 117 app_li = data['data']['content'] 118 # print(app_li) 119 # 二、解析app標籤數據 120 parse_index(app_li) 121 122 123 if __name__ == '__main__': 124 main()
1 from pymongo import MongoClient 2 3 # 一、連接mongoDB客戶端 4 # 參數1: mongoDB的ip地址 5 # 參數2: mongoDB的端口號 默認:27017 6 client = MongoClient('localhost', 27017) 7 # print(client) 8 9 # 二、進入tank_db庫,沒有則建立 10 # print(client['tank_db']) 11 12 # 三、建立集合 13 # print(client['tank_db']['people']) 14 15 # 四、給tank_db庫插入數據 16 17 # 1.插入一條 18 # data1 = { 19 # 'name': 'tank', 20 # 'age': 18, 21 # 'sex': 'male' 22 # } 23 # client['tank_db']['people'].insert(data1) 24 25 # 2.插入多條 26 # data1 = { 27 # 'name': 'tank', 28 # 'age': 18, 29 # 'sex': 'male' 30 # } 31 # data2 = { 32 # 'name': '戚志雲', 33 # 'age': 84, 34 # 'sex': 'female' 35 # } 36 # data3 = { 37 # 'name': '沈金金', 38 # 'age': 73, 39 # 'sex': 'male' 40 # } 41 # client['tank_db']['people'].insert([data1, data2, data3]) 42 # 43 # # 五、查數據 44 # # 查看全部數據 45 # data_s = client['tank_db']['people'].find() 46 # print(data_s) # <pymongo.cursor.Cursor object at 0x000002EEA6720128> 47 # # 須要循環打印全部數據 48 # for data in data_s: 49 # print(data) 50 # 51 # # 查看一條數據 52 # data = client['tank_db']['people'].find_one() 53 # print(data) 54 55 # 官方推薦使用 56 # 插入一條insert_one 57 # client['tank_db']['people'].insert_one() 58 # 插入多條insert_many 59 # client['tank_db']['people'].insert_many()