1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
| import random import time import requests, re from requests.packages import urllib3 from lxml import etree import xlwt from pandas import DataFrame
key_word = "植物生物技术Pbj" xpath_string = '//*[@id="js_content"]//text()' last_date = 2018
book = xlwt.Workbook(encoding='utf-8',style_compression=0) sheet = book.add_sheet(key_word,cell_overwrite_ok=True) col = ('title', 'author', 'content','category',"link","date") for i in range(0,6): sheet.write(0,i,col[i])
urllib3.disable_warnings()
title_list = [] link_list = [] cat_list = [] date_list = [] content_list = [] author_list = []
s = requests.Session()
headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0", "Host": "mp.weixin.qq.com", 'Referer': 'https://mp.weixin.qq.com/' } cookie_str = "" cookies = {}
def load_cookies(): global cookie_str, cookies for item in cookie_str.split(';'): sep_index = item.find('=') cookies[item[:sep_index]] = item[sep_index + 1:]
def quzao(content): if type(content) == str: i = re.sub('植物生物技术Pbj交流群', '', str(content)) i = re.sub('为了能更有效地帮助广大的科研工作者获取相关信息.*', '', str(i)) return i else: return ' '
def spider(): load_cookies() url = 'https://mp.weixin.qq.com' res = s.get(url = url, headers = headers, cookies = cookies, verify = False) if res.status_code == 200: print(res.url) token = re.findall(r'.*?token=(\d+)', res.url) if token: token = token[0] else: print('登陆失败') return print('token', token) url = 'https://mp.weixin.qq.com/cgi-bin/searchbiz' data = { "action": "search_biz", "begin": "0", "count": "5", "query": key_word, "token": token, "lang": "zh_CN", "f": "json", "ajax": "1" } res = s.get(url = url, params = data, cookies = cookies, headers = headers, verify = False) if res.status_code == 200: fakeid = res.json()['list'][0]['fakeid'] print('微信公众号fakeid', fakeid) page_size = 5 page_count = 278 cur_page = 1 l = 1 while cur_page <= page_count: url = 'https://mp.weixin.qq.com/cgi-bin/appmsg' data = { "action": "list_ex", "begin": str(page_size * (cur_page - 1)), "count": str(page_size), "fakeid": fakeid, "type": "9", "query": "", "token": token, "lang": "zh_CN", "f": "json", "ajax": "1" } time.sleep(random.randint(1, 5)) res = s.get(url = url, params = data, cookies = cookies, headers = headers, verify =False) if res.status_code == 200: print('开始爬取页数:', cur_page) app_msg_list = res.json()['app_msg_list'] for item in app_msg_list: item['post_date'] = time.strftime("%Y-%m-%d", time.localtime(int(item['update_time']))) if int(item['post_date'].split('-')[0])<last_date: continue if item['title'].find("|") != -1: title = item['title'].split("|")[1].strip() cat = item['title'].split("|")[0].strip() elif item['title'].find("|") != -1: title = item['title'].split("|")[1].strip() cat = item['title'].split("|")[0].strip() elif item['title'].find("│") != -1: title = item['title'].split("│")[1].strip() cat = item['title'].split("│")[0].strip() else: title = (item['title']) cat = 'N/A' title_list.append(title) date_list.append(item['post_date']) link_list.append(item['link']) author_list.append(key_word) cat_list.append(cat) response = requests.get(url = item['link'], headers = headers) print("正在解析网页" + str(item['link']) + '......') time.sleep(random.randint(1, 5)) tree_content = etree.HTML(response.text) try: content = tree_content.xpath(xpath_string) content = re.sub(r'\s+', '', ''.join(content)) content = quzao(content) except: content = '' content_list.append(content) print('解析文章"'+title+'"成功!') try: sheet.write(l , 0, title) sheet.write(l , 1, key_word) sheet.write(l , 2, content) sheet.write(l , 3, cat) sheet.write(l , 4, item['link']) sheet.write(l , 5, item['post_date']) savepath = './微信公众号_' + key_word + '_.xls' l += 1 if l % 20 == 0: book.save(savepath) print("数据备份成功!已保存" + str(l) + "条!") except: continue cur_page += 1 print('over!开始保存') data = {'title': title_list, 'author': author_list, 'content': content_list,'category': cat_list,"link":link_list,"date":date_list} df = DataFrame(data) df.to_excel('./微信公众号_' + key_word + '_.xlsx') print('保存成功!') spider()
|