Python網路資料擷取3-資料存到CSV以及MySql
先熱熱身,下載某個頁面的所有圖片。
import requestsfrom bs4 import BeautifulSoupheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)' ' Chrome/52.0.2743.116 Safari/537.36 Edge/15.16193'}start_url = 'https://www.pythonscraping.com'r = requests.get(start_url, headers=headers)soup = BeautifulSoup(r.text, 'lxml')# 擷取所有img標籤img_tags = soup.find_all('img')for tag in img_tags:print(tag['src'])
http://pythonscraping.com/img/lrg%20(1).jpg
將網頁Table Store到CSV檔案中
以這個網址為例,有好幾個表格,我們對第一個表格進行爬取。Wiki-各種編輯器的比較
import csvimport requestsfrom bs4 import BeautifulSoupheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)' ' Chrome/52.0.2743.116 Safari/537.36 Edge/15.16193'}url = 'https://en.wikipedia.org/wiki/Comparison_of_text_editors'r = requests.get(url, headers=headers)soup = BeautifulSoup(r.text, 'lxml')# 只要第一個表格rows = soup.find('table', class_='wikitable').find_all('tr')# csv寫入時候每寫一行會有一空行被寫入,所以設定newline為空白with open('editors.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f)for row in rows: csv_row = []for cell in row.find_all(['th', 'td']): csv_row.append(cell.text) writer.writerow(csv_row)
需要注意的有一點,開啟檔案的時候需要指定newline='',因為寫入csv檔案時,每寫入一行就會有一空行被寫入。
從網路讀取CSV檔案
上面介紹了將網頁內容存到CSV檔案中。如果是從網上擷取到了CSV檔案呢?我們不希望下載後再從本地讀取。但是網路請求的話,返回的是字串而非檔案對象。csv.reader()需要傳入一個檔案對象。故需要將擷取到的字串轉換成檔案對象。Python的內建庫,StringIO和BytesIO可以將字串/位元組當作檔案一樣來處理。對於csv模組,要求reader迭代器返回字串類型,所以使用StringIO,如果處理位元據,則用BytesIO。轉換為檔案對象,就能用CSV模組處理了。
下面的代碼最為關鍵的就是data_file = StringIO(csv_data.text)將字串轉換為類似檔案的對象。
from io import StringIOimport csvimport requestscsv_data = requests.get('http://pythonscraping.com/files/MontyPythonAlbums.csv')data_file = StringIO(csv_data.text)reader = csv.reader(data_file)for row in reader:print(row)
['Name', 'Year']["Monty Python's Flying Circus", '1970']['Another Monty Python Record', '1971']["Monty Python's Previous Record", '1972']['The Monty Python Matching Tie and Handkerchief', '1973']['Monty Python Live at Drury Lane', '1974']['An Album of the Soundtrack of the Trailer of the Film of Monty Python and the Holy Grail', '1975']['Monty Python Live at City Center', '1977']['The Monty Python Instant Record Collection', '1977']["Monty Python's Life of Brian", '1979']["Monty Python's Cotractual Obligation Album", '1980']["Monty Python's The Meaning of Life", '1983']['The Final Rip Off', '1987']['Monty Python Sings', '1989']['The Ultimate Monty Python Rip Off', '1994']['Monty Python Sings Again', '2014']
DictReader可以像操作字典那樣擷取資料,把表的第一行(一般是標題)作為key。可訪問每一行中那個某個key對應的資料。
每一行資料都是OrderDict,使用Key可訪問。看上面列印資訊的第一行,說明由Name和Year兩個Key。也可以使用reader.fieldnames查看。
from io import StringIOimport csvimport requestscsv_data = requests.get('http://pythonscraping.com/files/MontyPythonAlbums.csv')data_file = StringIO(csv_data.text)reader = csv.DictReader(data_file)# 查看Keyprint(reader.fieldnames)for row in reader:print(row['Year'], row['Name'], sep=': ')
['Name', 'Year']1970: Monty Python's Flying Circus1971: Another Monty Python Record1972: Monty Python's Previous Record1973: The Monty Python Matching Tie and Handkerchief1974: Monty Python Live at Drury Lane1975: An Album of the Soundtrack of the Trailer of the Film of Monty Python and the Holy Grail1977: Monty Python Live at City Center1977: The Monty Python Instant Record Collection1979: Monty Python's Life of Brian1980: Monty Python's Cotractual Obligation Album1983: Monty Python's The Meaning of Life1987: The Final Rip Off1989: Monty Python Sings1994: The Ultimate Monty Python Rip Off2014: Monty Python Sings Again
儲存資料
大資料存放區與資料互動能力, 在新式的程式開發中已經是重中之重了.
儲存媒體檔案的2種主要方式: 只擷取url連結, 或直接將源檔案下載下來
直接引用url連結的優點:
爬蟲運行得更快,耗費的流量更少,因為只要連結,不需要下載檔案。
可以節省很多儲存空間,因為只需要儲存 URL 連結就可以。
儲存 URL 的代碼更容易寫,也不需要實現檔案下載代碼。
不下載檔案能夠降低目標主機伺服器的負載。
直接引用url連結的缺點:
這些內嵌在網站或應用中的外站 URL 連結被稱為盜鏈(hotlinking), 每個網站都會實施防盜鏈措施。
因為連結檔案在別人的伺服器上,所以應用就要跟著別人的節奏運行了。
盜鏈是很容易改變的。如果盜鏈圖片放在部落格上,要是被對方伺服器發現,很可能被惡搞。如果 URL 連結存起來準備以後再用,可能用的時候連結已經失效了,或者是變成了完全無關的內容。
python3的urllib.request.urlretrieve可以根據檔案的url下載檔案:
from urllib.request import urlretrievefrom urllib.request import urlopenfrom bs4 import BeautifulSouphtml = urlopen("http://www.pythonscraping.com")bsObj = BeautifulSoup(html)imageLocation = bsObj.find("a", {"id": "logo"}).find("img")["src"]urlretrieve (imageLocation, "logo.jpg")
csv(comma-separated values, 逗號分隔值)是儲存表格式資料的熱門檔案格式
網路資料擷取的一個常用功能就是擷取html表格並寫入csv
除了使用者定義的變數名,mysql是不區分大小寫, 習慣上mysql關鍵字用大寫表示
串連與遊標(connection/cursor)是資料庫編程的2種模式:
串連模式除了要串連資料庫之外, 還要發送資料庫資訊, 處理復原操作, 建立遊標對象等
一個串連可以建立多個遊標, 一個遊標跟蹤一種狀態資訊, 比如資料庫的使用狀態. 遊標還會包含最後一次查詢執行的結果. 通過調用遊標函數, 如fetchall擷取查詢結果
遊標與串連使用完畢之後,務必要關閉, 否則會導致串連泄漏, 會一直消耗資料庫資源
使用try ... finally語句保證資料庫連接與遊標的關閉
讓資料庫更高效的幾種方法:
給每張表都增加id欄位. 通常資料庫很難智能地選擇主鍵
用智能索引, CREATE INDEX definition ON dictionary (id, definition(16));
選擇合適的範式
發送Email, 通過爬蟲或api擷取資訊, 設定條件自動發送Email! 那些訂閱郵件, 肯定就是這麼來的!
儲存連結之間的聯絡
比如連結A,能夠在這個頁面裡找到連結B。則可以表示為A -> B。我們就是要儲存這種聯絡到資料庫。先建表:
pages表只儲存連結url。
CREATE TABLE `pages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `url` varchar(255) DEFAULT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`))
links表儲存連結的fromId和toId,這兩個id和pages裡面的id是一致的。如1 -> 2就是pages裡id為1的url頁面裡可以訪問到id為2的url的意思。
CREATE TABLE `links` ( `id` int(11) NOT NULL AUTO_INCREMENT, `fromId` int(11) DEFAULT NULL, `toId` int(11) DEFAULT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`)
上面的建表語句看起來有點臃腫,我是先用視覺化檢視建表後,再用show create table pages這樣的語句查看的。
import reimport pymysqlimport requestsfrom bs4 import BeautifulSoupheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)' ' Chrome/52.0.2743.116 Safari/537.36 Edge/15.16193'}conn = pymysql.connect(host='localhost', user='root', password='admin', db='wiki', charset='utf8')cur = conn.cursor()def insert_page_if_not_exists(url): cur.execute(f"SELECT * FROM pages WHERE url='{url}';")# 這條url沒有插入的話if cur.rowcount == 0:# 那就插入cur.execute(f"INSERT INTO pages(url) VALUES('{url}');") conn.commit()# 剛插入資料的idreturn cur.lastrowid# 否則已經存在這條資料,因為url一般是唯一的,所以擷取一個就行,取腳標0是獲得idelse:return cur.fetchone()[0]def insert_link(from_page, to_page):print(from_page, ' -> ', to_page) cur.execute(f"SELECT * FROM links WHERE fromId={from_page} AND toId={to_page};")# 如果查詢不到資料,則插入,插入需要兩個pages的id,即兩個urlif cur.rowcount == 0: cur.execute(f"INSERT INTO links(fromId, toId) VALUES({from_page}, {to_page});") conn.commit()# 連結去重pages = set()# 得到所有連結def get_links(page_url, recursion_level):global pagesif recursion_level == 0:return# 這是剛插入的連結page_id = insert_page_if_not_exists(page_url) r = requests.get('https://en.wikipedia.org' + page_url, headers=headers) soup = BeautifulSoup(r.text, 'lxml') link_tags = soup.find_all('a', href=re.compile('^/wiki/[^:/]*$'))for link_tag in link_tags:# page_id是剛插入的url,參數裡再次調用了insert_page...方法,獲得了剛插入的url裡能去往的url列表# 由此形成聯絡,比如剛插入的id為1,id為1的url裡能去往的id有2、3、4...,則形成1 -> 2, 1 -> 3這樣的聯絡insert_link(page_id, insert_page_if_not_exists(link_tag['href']))if link_tag['href'] not in pages: new_page = link_tag['href'] pages.add(new_page)# 遞迴尋找, 只能遞迴recursion_level次get_links(new_page, recursion_level - 1)if __name__ == '__main__':try: get_links('/wiki/Kevin_Bacon', 5)except Exception as e:print(e)finally: cur.close() conn.close()
1 -> 22 -> 11 -> 21 -> 33 -> 44 -> 54 -> 64 -> 74 -> 84 -> 44 -> 44 -> 94 -> 93 -> 1010 -> 1110 -> 1210 -> 1310 -> 1410 -> 1510 -> 1610 -> 1710 -> 1810 -> 1910 -> 2010 -> 21...
看列印的資訊,一目瞭然。看前兩行列印,pages表裡id為1的url可以訪問id為2的url,同時pages表裡id為2的url可以訪問id為1的url...依次類推。
首先需要使用insert_page_if_not_exists(page_url)獲得連結的id,然後使用insert_link(fromId, toId)形成聯絡。fromId是當前頁面的url,toId則是從當前頁面能夠去往的url的id,這些能去往的url用bs4找到以列表形式返回。當前所處的url即page_id,所以需要在insert_link的第二個參數中,再次調用insert_page_if_not_exists(link)以獲得列表中每個url的id。由此形成了聯絡。比如剛插入的id為1,id為1的url裡能去往的id有2、3、4...,則形成1 -> 2, 1 -> 3這樣的聯絡。
看下資料庫。下面是pages表,每一個id都對應一個url。
然後下面是links表,fromId和toId就是pages中的id。當然和列印的資料是一樣的咯,不過列印了看看就過去了,存下來的話哪天需要分析這些資料就大有用處了。