标签:mamicode init false sci detail 响应 with name ensure
content_list = re.findall(r‘<a href="/detail-.*">(.+?)</a>‘, html_str)
content_list = re.findall(r‘<div class="j-r-list-c-desc">\s*<a href="/detail-.*">(.+?)</a>‘, html_str)
1 import requests 2 import re 3 import json 4 5 class NeihanSpider(object): 6 """内涵段子,百思不得其姐,正则爬取一页的数据""" 7 def __init__(self): 8 self.temp_url = ‘http://www.budejie.com/text/{}‘ # 网站地址,给页码留个可替换的{} 9 self.headers = { 10 ‘User-Agent‘: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36‘, 11 } 12 13 def pass_url(self, url): # 发送请求,获取响应 14 print(url) 15 response = requests.get(url, headers=self.headers) 16 return response.content.decode() 17 18 def get_first_page_content_list(self, html_str): # 提取第一页的数据 19 content_list = re.findall(r‘<div class="j-r-list-c-desc">\s*<a href="/detail-.*">(.+?)</a>‘, html_str) # 非贪婪匹配 20 return content_list 21 22 def save_content_list(self, content_list): 23 with open(‘neihan.txt‘, ‘a‘, encoding=‘utf-8‘) as f: 24 for content in content_list: 25 f.write(json.dumps(content, ensure_ascii=False)) 26 f.write(‘\n‘) # 换行 27 print(‘成功保存一页!‘) 28 29 def run(self): # 实现主要逻辑 30 for i in range(20): # 只爬取前20页数据 31 # 1. 构造url 32 # 2. 发送请求,获取响应 33 html_str = self.pass_url(self.temp_url.format(i+1)) 34 # 3. 提取数据 35 content_list = self.get_first_page_content_list(html_str) 36 # 4. 保存 37 self.save_content_list(content_list) 38 39 if __name__ == ‘__main__‘: 40 neihan = NeihanSpider() 41 neihan.run()
标签:mamicode init false sci detail 响应 with name ensure
原文地址:https://www.cnblogs.com/springionic/p/11110314.html