(每一天都是屬於你的!)
Python對於初學后鞏固基礎的人還是更多的來接觸python爬蟲會更好一些,在Python爬蟲中包含很多基礎部分知識,並且在項目中會提升你的成功感!加油!
我在工作之余時間,把Python的爬蟲基礎內容整理了一下,資料因為太多所以都放在QQ群內了,需要的可以來---607021567。
今天整理了一個兩個網站的小說閱讀平台的爬蟲,將兩個網站的小說可按自有的格式抓取下來自動生成txt文件。
項目介紹:
--Python爬蟲
--模塊:requests,BeautifulSoup,time
--分析:request模塊作用於網站的連接與處理,BeautifulSoup作用於源碼中的代碼分析與抓取,time主要是在我們抓取的過程中加入時間限制(這個主要是應對有網站監控的,這里我們就不需要了)
因為這里沒有涉及到數據庫相關的操作,所以沒有對數據庫的相關詳細內容,但是我會將Python與mongodb、MySQL、Sqlserver的連接方式的代碼會附贈在下面。
一、網頁分析:
首先步步分析網頁內容:https://www.booktxt.net/6_6453/2529786.html,cookie信息--F12鍵。
這里面有很多廣告,不過可以不用去理它們,首先獲取到我們需要的網址:
1 # -*- coding:utf-8 -*- 2 import requests 3 from bs4 import BeautifulSoup 4 import time 5 6 def project(url,page): 7 #url='http://www.23us.so/files/article/html/1/1809/877404.html' #大主宰 8 #url='http://www.23us.so/files/article/html/6/6100/2193573.html' #天下無雙 9 #url='https://www.booktxt.net/6_6453/2529786.html' #元尊 10 headers={"Cookie": "jieqiVisitId=article_articleviews%3D6453; cscpvrich87", 11 "Host": "www.booktxt.net", 12 "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0", 13 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"} 14 r =requests.get(url,headers,timeout=30) 15 h = r.content
這里主要使用request模塊獲取網址的源碼,h--就是我們所獲取的源碼,你可以測試的時候print出來。
二、源碼分析
我們這里直接在網頁中來查看源碼:網頁中右鍵查看源碼。
這里我們注意到文本的內容包含在<div id="content">的標簽內,所以接下來我們使用bs4來處理。
1 soup = BeautifulSoup(h, "html.parser") 2 a1 = soup.find('div',class_="bookname").h1 3 text_da(a1.get_text().encode('utf-8')+'\n\n\n') 4 a = soup.find('div',id='content') 5 text_da(a.get_text().encode('utf-8')+'\n\n\n')
每一行分開解釋:
1、使用BeautifulSoup模塊,其中"html.parser"是模塊內置函數,對源碼的分析,這樣我們就獲取到網址的bs4源碼。
2、首先是獲取小說中的標題,soup.find--是獲取源碼中第一個div標簽class=“bookname”下的h1標簽,當前我們獲取到h1標簽所有內容包括標簽,但是我們需要獲取到文本內容。
3、獲取獲得標簽內的文本內容--a1.get_text(),這里的encode('utf-8')是將我們獲取的內容需要轉碼,不然是亂碼的狀態。
4、獲取我們主要的文本內容--同理,需要獲得文本內容的標簽div
5、獲得文本內容。
三、分頁操作
因為我們瀏覽的頁面會有分頁,所有這里也是我們需要注意的地方。
這里的下一章按鈕,就是我們的突破點:
1 b = soup.find('div',class_='bottem2') 2 if b: 3 a = b.find_all('a') 4 #shuurl = 'http://www.23us.so'+a[-1]['href'] 5 shuurl = 'https://www.booktxt.net' + a[-2]['href'] 6 #print shuurl 7 page=page+1 8 project(shuurl,page)
我們在源碼中獲取到的下一章的網址位於a標簽內。
3行、--我們獲取所有的a標簽。
5行、a[-2]是獲取我們倒數第二個標簽也就是我們的下一章標簽,【’href‘】--是獲得a標簽內的href的內容也就是我們的地址,這里需要拼接字符串。
7行、是抓取的注釋內容,稍后在源碼中你會看到效果
8行、有的小伙伴注意到了,這里是調用函數,函數的名字就是我們一開始定義的函數,就是它自己本身。
四、寫入文件
接下來,我們的主要價值數據獲取到,但是我們需要它成為txt文件,所以我寫了一個函數,在上面的函數體中直接調用就可以了。
1 def text_da(text): 2 fo = open("foo.txt", "a") 3 fo.write(text) 4 5 # 關閉打開的文件 6 fo.close()
五、啟動函數
最后一步,就是我們的啟動程序代碼。
1 if __name__ == '__main__': 2 page=1 3 url = 'https://www.booktxt.net/6_6453/2529786.html' # 元尊 4 project(url,page)
這里主要是python的內置函數,作為啟動py文件內的函數。
六、源碼
哦!忘了源碼-----
1 # -*- coding:utf-8 -*- 2 import requests 3 from bs4 import BeautifulSoup 4 import time 5 6 def project(url,page): 7 #url='http://www.23us.so/files/article/html/1/1809/877404.html' #大主宰 8 #url='http://www.23us.so/files/article/html/6/6100/2193573.html' #天下無雙 9 #url='https://www.booktxt.net/6_6453/2529786.html' #元尊 10 headers={"Cookie": "jieqiVisitId=article_articleviews%3D6453; cscpvrich8793_fidx=4; __tins__19219364=%7B%22sid%22%3A%201527749231776%2C%20%22vd%22%3A%204%2C%20%22expires%22%3A%201527751067272%7D; __51cke__=; __51laig__=4; Hm_lvt_6949867c34e7741ebac3943050f04833=1527749232; Hm_lpvt_6949867c34e7741ebac3943050f04833=1527749267; cscpvcouplet8792_fidx=4; cscpvrich8791_fidx=4", 11 "Host": "www.booktxt.net", 12 "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:60.0) Gecko/20100101 Firefox/60.0", 13 "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"} 14 r =requests.get(url,headers,timeout=30) 15 h = r.content 16 #print h 17 soup = BeautifulSoup(h, "html.parser") 18 #a = soup.find('dd',id='contents') 19 #print a.get_text() 20 a1 = soup.find('div',class_="bookname").h1 21 text_da(a1.get_text().encode('utf-8')+'\n\n\n') 22 a = soup.find('div',id='content') 23 text_da(a.get_text().encode('utf-8')+'\n\n\n') 24 print '第'+str(page)+'章!' 25 #b = soup.find('dd',id='footlink') 26 b = soup.find('div',class_='bottem2') 27 if b: 28 a = b.find_all('a') 29 #shuurl = 'http://www.23us.so'+a[-1]['href'] 30 shuurl = 'https://www.booktxt.net' + a[-2]['href'] 31 #print shuurl 32 page=page+1 33 project(shuurl,page) 34 35 def text_da(text): 36 fo = open("foo.txt", "a") 37 fo.write(text) 38 39 # 關閉打開的文件 40 fo.close() 41 42 if __name__ == '__main__': 43 page=1 44 url = 'https://www.booktxt.net/6_6453/2529786.html' # 元尊 45 project(url,page)
對了!還有Python對於數據庫的連接操作,我這里直接就貼源碼了,其中很多的內容我都注釋了!不懂的可以加群---607021567(需要驗證信息,因為我不知道來的是朋友還是敵人)
1 # -*- coding:utf-8 -*- 2 import pymongo 3 from pymongo import MongoClient 4 import json 5 #MONGODB 6 #連接 7 client = MongoClient('mongodb://localhost') 8 db = client.test 9 table='test' 10 #db[table].insert({'user_id':2,'name':'zhu'}) 11 #db[table].update({'name':'zhu'},{'$set':{'user_id':2}}) 12 #db[table].remove({'name':'zhu'}) 13 #查詢結果排序(key:1或者-1)升序或者降序 14 a = db[table].find().sort("user_id",1) 15 print a 16 for i in a: 17 print i 18 19 #db.authenticate('test','test') 20 21 """table = 'imi_product' 22 a = db[table].find({'partno':'NEN1FX6'}).limit(1) 23 detailList = [] 24 for i in a: 25 if (i.get("specs")): 26 specary = i.get("specs") 27 for i in specary: 28 detailList.append({"left": i, "right": specary[i]}) 29 print detailList 30 for i in detailList: 31 print i.get('right') 32 #查詢和增加 33 #db[table].insert({'sn':1,'b':'b'}) 34 #更改 35 #db[table].update({'sn':1},{'$set':{'b':'sda'}}) 36 #刪除 37 #刪除name=lisi的全部記錄 38 #db[table].remove({'sn': 1}) 39 #刪除集合里的所有記錄 40 #db.users.remove() 41 # (>) 大於 - $gt 42 # (<) 小於 - $lt 43 # (>=) 大於等於 - $gte 44 # (<= ) 小於等於 - $lte 45 #a = db[table] 46 #print a.find_one()""" 47 48 49 50 #SQLSERVER 51 """import pyodbc 52 import MySQLdb 53 MSSQL_INFO = {"hostname":"localhost","username":"","password":"","dbname":"oneice"} 54 strconn= 'DRIVER={SQL Server};SERVER='+MSSQL_INFO.get("hostname")+';DATABASE='+MSSQL_INFO.get("dbname")+';UID='+MSSQL_INFO.get("username")+';PWD='+MSSQL_INFO.get("password") 55 db = pyodbc.connect(strconn) 56 sqldb = db.cursor() 57 #查詢 58 sql = 'select * from news where news_id=1' 59 #添加 60 sql ="insert into news (news_title,news_author,news_summary,news_content,news_pic) values ('haha','happy','Iriji','little','12dsa')" 61 #刪除 62 sql ="delete from news where news_id=5" 63 sqldb.execute(sql) 64 sqldb.commit() 65 #查詢 66 row = sqldb.fetchone() 67 print row[1] 68 #存儲過程 69 sqldb.execute("{call 存儲過程名字 (參數)}", '上傳的參數') 70 q = sqldb.fetchone()/fetchall() 71 sqldb.commit() 72 if q: 73 print q[1]"""
這里包含這Python調用SQLSERVER的存儲過程和基本操和MONGODB的基本操作!