1. 程式人生 > >python爬蟲學習:第一爬_快眼看書排行榜

python爬蟲學習:第一爬_快眼看書排行榜

font n) 對象 file 叠代器 get quest client 有一個

 1 import json
 2 import re
 3 from urllib.request import urlopen    # urllib用法:https://www.jb51.net/article/65279.htm
 4 
 5 # 思路:通過url獲取網頁內容--》匹配需要內容---》拿到內容寫入文件
 6 
 7 
 8 def get_page(url):
 9     """
10     獲得網頁代碼字符串,以便操作
11     :param url: 傳入網址
12     :return:  返回utf編碼得字符串
13     """
14  # respond對象有一個方法叫著read(),用它讀出來是一個bytes類型得數據,需要轉碼
15 respond = urlopen(url) 16 return respond.read().decode(utf-8) 17 # 如果不用,將返回得是一個對象 <http.client.HTTPResponse object at 0x000001E25553EE10> 18 19 # 將得到的字符串傳入,通過正則匹配出需要的內容,返回 20 def parse_page(s_strfile, pattern): 21 """ 22 通過正則去匹配傳入的字符串,得到想要的內容 23 為節約時間,因為每次都要用相同的正則規則去匹配我想要的內容,故可以將正則配置成一個對象,然後對象通過調用方法查值
24 為節約空間,可用叠代器取值,乘上將對象封裝成一個生成器,每次取一個,節約內存 25 :param s_strfile: 26 :return: 27 """ 28 # com = re.compile(‘<td class="s">.*?<a href=.*?>(?P<x_name>.*?)</a>.*?<a href=.*?>(?P<x_title>.*?)</a>‘ 29 # ‘.*?<td class="t">(?P<x_time>.*?)</td>‘, re.S)
30 # 兩行和一行一樣的效果 31 # com = re.compile( 32 # ‘<td class="s">.*?<a href=.*?>(?P<x_name>.*?)</a>.*?<a href=.*?>(?P<x_title>.*?)</a>.*?<td class="t">(?P<x_time>.*?)</td>‘, 33 # re.S) 34 # 上面是將正則通過方法compile構建成一個對象 35 36 # 先試著通過findall可以全部取出,但很占內存,故查找結果存儲,計劃構建成一個生成器,一次取一個 37 # page = com.findall(s_strfile) 38 # print(page) 39 40 ret = pattern.finditer(s_strfile) # 此方法比findall要節省內存,取值用all 41 for i in ret: 42 yield {name: i.group(x_name), 43 title: i.group(x_title), 44 time: i.group(x_time)} 45 46 47 def main(page_num, pattern): 48 """ 49 接收運行次數及正則規則,寫入文件 50 :param page_num: 51 :param pattern: 52 :return: 53 """ 54 url = http://booksky.99lb.net/sodupaihang/page%s % page_num 55 response_html_code = get_page(url) 56 ret = parse_page(response_html_code, pattern) 57 with open(xiaoshuo_info.txt, a, encoding=utf-8) as f: 58 for data in ret: 59 write_line_str = json.dumps(data, ensure_ascii=False) # json 為字符串 60 f.write(‘‘.join([write_line_str, \n])) 61 62 63 # 編譯正則規則為一個對象,放在全局變量,只需編譯一次即可,省時間 64 pattern = re.compile( 65 <td class="s">.*?<a href=.*?>(?P<x_name>.*?)</a>.*?<a href=.*?>(?P<x_title>.*?)66 </a>.*?<td class="t">(?P<x_time>.*?)</td>, 67 re.S) 68 69 if __name__ == __main__: 70 for num in range(1, 11): 71 main(num, pattern)

python爬蟲學習:第一爬_快眼看書排行榜