本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,著作權歸原作者所有,如有問題請及時聯系我們以作處理,
以下文章來源于云+社區,作者 聽城
轉載地址
https://blog.csdn.net/fei347795790?t=1
主要內容
- requests設定headers,防止反爬
- 爬取內容
- 結果json保存
- 多執行緒抓取
設定headers
設定headers的主要目的就是防止用戶請求被請求頁面判定為惡意請求,最基本的就是要讓用戶的請求模擬瀏覽器請求的方式,通常在headers設定user-agent來起到模擬瀏覽器的方式,
session = requests.Session() headers = { 'Connection': 'keep-alive', 'Accept': 'text/html, */*; q=0.01', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6' }
爬取內容
我們使用正則運算式方式來獲取我們想要的資料,這里會用re.compile()函式,該函式根據包含的正則運算式的字串創建模式物件,可以實作更有效率的匹配,在直接使用字串表示的正則運算式進行search,match和findall操作時,python會將字串轉換為正則運算式物件,而使用compile完成一次轉換之后,在每次使用模式的時候就不用重復轉換,當然,使用re.compile()函式進行轉換后,re.search(pattern, string)的呼叫方式就轉換為 pattern.search(string)的呼叫方式,
pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="https://www.cnblogs.com/hhh188764/p/(.*?)".*?name">' + '<a.*?>(.*?)</a>.*?"star">(.*?)</p>.*?releasetime">(.*?)</p>' + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S) # 匹配所有符合條件的內容 items = re.findall(pattern, html)
結果json保存
# ensure_ascii=False是為了中文正常顯示 with open('result.txt', 'a', encoding='utf-8') as f: f.write(json.dumps(content, ensure_ascii=False) + '\n')
多執行緒抓取
from multiprocessing import Pool pool = Pool() pool.map(main,[i*10 for i in range(10)])
全部代碼
import re import os import json import requests from multiprocessing import Pool from requests.exceptions import RequestException session = requests.Session() headers = { 'Connection': 'keep-alive', 'Accept': 'text/html, */*; q=0.01', 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36', 'Accept-Encoding': 'gzip, deflate, sdch', 'Accept-Language': 'zh-CN,zh;q=0.8,ja;q=0.6' } def get_one_page(url): try: response = session.get(url,headers=headers) if response.status_code == 200: return response.text return None except RequestException: return 'RequestException' def parse_one_page(html): print('parse page') #re.S是為了匹配換行符 pattern = re.compile('<dd>.*?board-index.*?>(\d+)</i>.*?data-src="https://www.cnblogs.com/hhh188764/p/(.*?)".*?name">' + '<a.*?>(.*?)</a>.*?"star">(.*?)</p>.*?releasetime">(.*?)</p>' + '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>', re.S) # 匹配所有符合條件的內容 items = re.findall(pattern, html) for item in items: yield { 'index': item[0], 'image': item[1], 'title': item[2], 'actor': item[3].strip()[3:], 'time': item[4].strip()[5:], 'score': item[5] + item[6] } def write_to_file(content): ''' 將文本資訊寫入檔案 ''' with open('result.txt', 'a', encoding='utf-8') as f: f.write(json.dumps(content, ensure_ascii=False) + '\n') def save_image_file(url, path): ''' 保存電影封面 ''' ir = requests.get(url) if ir.status_code == 200: with open(path, 'wb') as f: f.write(ir.content) f.close() def main(offset): url = 'http://maoyan.com/board/4?offset=' + str(offset) html = get_one_page(url) # 封面檔案夾不存在則創建 if not os.path.exists('covers'): os.mkdir('covers') for item in parse_one_page(html): #print(item) write_to_file(item) save_image_file(item['image'], 'covers/' + '%03d' % int(item['index']) + item['title'] + '.jpg') if __name__ == '__main__': # for i in range(10): # main(i+10) pool = Pool() pool.map(main,[i*10 for i in range(10)])
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/132231.html
標籤:Python
上一篇:十六大Python面試題!看完面試官給了我40K的薪資
下一篇:字串 數字 轉換
