├── .gitignore ├── LICENSE ├── README.md ├── article.py ├── auto.bat ├── config.py ├── database.py ├── gadget.py ├── post.py └── sina.sql /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/* 2 | log/* 3 | 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sinaCrawlerV 2 | easy program to backup posts and comments of specify user in sina 3 | 简易爬虫抓取指定用户的微博和微博文章 4 | 5 | ## Requirement: 6 | - python 3.6 7 | + extension: 8 | * bs4 9 | * lxml 10 | * pymysql 11 | 12 | - mysql 5.6 13 | 14 | ## Function: 15 | - database.py 封装了各种mysql操作 16 | - post.py 抓取微博,每次抓取到上次抓取的时间为止 17 | - article.py 抓取文章,同上 18 | - gadget.py 用到的各种小工具 19 | - config.py 需要用到的参数 20 | 21 | ## Usage: 22 | - 创建数据表:运行sina.sql创建数据表 23 | - 完善config.py的参数,抓取微博使用移动端的请求链接;抓取文章需要登录,这里手动登录后,查看移动端的异步请求,复制Request Header里面的cookie出来使用 24 | - 命令行终端cd到py文件所在目录,运行pyhton.py和article.py,或修改auto.bat文件的cd路径,双击改文件开始抓取 25 | 26 | ## Todo: 27 | - OOP改写 28 | - 自动登录 29 | 30 | -------------------------------------------------------------------------------- /article.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | aritcle.py 6 | ~~~~~~~~~~~~~~~~~ 7 | Crawl aritcle content 8 | """ 9 | import requests 10 | import json 11 | from bs4 import BeautifulSoup 12 | import re 13 | from config import * 14 | from database import * 15 | from gadget import * 16 | 17 | def getArticle(page, latestTimestamp, conn): 18 | '''Get Article Content: Get article id and then get content with it''' 19 | 20 | # convert timestamp to date format 21 | timeLocal = getDate(latestTimestamp) 22 | breakCount = 0 23 | print("=====开始抓取时间[%s]之后的微博文章=====" % timeLocal) 24 | print('开始抓取文章列表第%s页' % page) 25 | 26 | url = articleListUrlFormat.format(page) 27 | data = requests.get(url, headers = articleHeaders) 28 | data.encoding = 'utf-8' 29 | data = json.loads(data.text) 30 | if 'ok' in data and data['ok'] == 0: 31 | print("抓取完毕或抓取失败,请重设Cookie或休息一会!") 32 | exit() 33 | for content in data['data']['cards']: 34 | kwArticle = {} 35 | # if 'card_type' is 9 36 | if content['card_type'] == 9: 37 | kwArticle['add_time'] = getTimestamp(content['mblog']['created_at']) 38 | kwArticle['title'] = content['mblog']['page_info']['page_title'] 39 | 40 | object_id = content['mblog']['page_info']['object_id'] 41 | kwArticle['article_id'] = object_id.split(":")[1] 42 | articleTuple = getArticleContent(kwArticle['article_id'],1) 43 | 44 | if articleTuple[0] == '': 45 | saveFailId(kwArticle['article_id'],kwArticle['title']) 46 | continue 47 | kwArticle['content'] = articleTuple[0] 48 | 49 | elif content['card_type'] == 11 and content['card_group'][0]['card_type'] == 9: 50 | kwArticle['add_time'] = getTimestamp(content['card_group'][0]['mblog']['created_at']) 51 | kwArticle['title'] = content['card_group'][0]['mblog']['page_info']['page_title'] 52 | 53 | object_id = content['card_group'][0]['mblog']['page_info']['object_id'] 54 | kwArticle['article_id'] = object_id.split(":")[1] 55 | articleTuple = getArticleContent(kwArticle['article_id'],1) 56 | 57 | if articleTuple[0] == '': 58 | saveFailId(kwArticle['article_id'],kwArticle['title']) 59 | continue 60 | 61 | kwArticle['content'] = articleTuple[0] 62 | 63 | elif content['card_type'] == 8: 64 | regex = re.compile('id=.*?&') 65 | result = regex.findall(content['scheme']) 66 | kwArticle['article_id'] = result[0].rstrip("&").split("=")[1] 67 | kwArticle['title'] = content['title_sub'] 68 | 69 | urlFormat = r'http://card.weibo.com/article/aj/articleshow?cid={}' 70 | urlArticle = urlFormat.format(kwArticle['article_id']) 71 | articleTuple = getArticleContent(kwArticle['article_id'], 2) 72 | if articleTuple[0] == '': 73 | saveFailId(kwArticle['article_id'],kwArticle['title']) 74 | continue 75 | 76 | kwArticle['add_time'] = getTimestamp(articleTuple[1]) 77 | kwArticle['content'] = articleTuple[0] 78 | if kwArticle: 79 | # if kwArticle['add_time'] > 0: 80 | if kwArticle['add_time'] > latestTimestamp: 81 | print('保存文章:%s' % kwArticle['title']) 82 | insert_data('wb_mzm_article', conn, **kwArticle) 83 | print("保存成功!\n") 84 | else: 85 | print('已抓取,不写入') 86 | breakCount = breakCount + 1 87 | # if reach the limit fail times,stop 88 | if breakCount == 5: 89 | # close database connection 90 | closeConn(conn) 91 | print('已经抓取完毕,程序结束...') 92 | exit() 93 | 94 | def getArticleContent(id,card_type): 95 | '''Get content by id''' 96 | 97 | object_id = '1022:' + id 98 | url = articleUrlFormat.format(object_id = object_id, id = id) 99 | response = requests.get(url, headers = articleHeaders) 100 | response.encoding = 'utf-8'; 101 | soup = BeautifulSoup(response.text,'lxml') 102 | 103 | # if article content contains in script tag, parse content in it 104 | if len(soup.findAll("script")) > 1 and card_type == 1: 105 | jsText = soup.findAll("script")[1].text 106 | 107 | # Extract value of content,add brackets in regex to make it only return the brackets part 108 | regex = re.compile('\"content\":(.*)') 109 | result = regex.findall(jsText) 110 | 111 | # Get rid of html tag 112 | resultSoup = BeautifulSoup(result[0], 'lxml') 113 | return resultSoup.body.get_text().strip(',').strip('"'), '' 114 | 115 | # if article content return from api 116 | else: 117 | urlFormat = r'http://card.weibo.com/article/aj/articleshow?cid={}' 118 | url = urlFormat.format(id) 119 | response = requests.get(url, headers = articleHeaders) 120 | if response: 121 | response.encoding = 'utf-8' 122 | content = json.loads(response.text) 123 | parseContent = json.dumps(content).encode('utf-8').decode('unicode_escape') 124 | 125 | if type(content) == str or '原文章已被删除' in parseContent or '正在加载内容' in parseContent: 126 | return '','' 127 | 128 | articleHTML = content['data']['article'] 129 | articleSoup = BeautifulSoup(articleHTML,'lxml') 130 | articleContent = articleSoup.find('div', class_='WBA_content').text 131 | articleTime = articleSoup.find('span', class_='time').text 132 | return articleContent.strip(',').strip('"'), articleTime 133 | else: 134 | return '','' 135 | 136 | if __name__ == '__main__': 137 | conn = db_connector() 138 | latestTimestamp = selectData(conn,'wb_mzm_article',4) 139 | 140 | if latestTimestamp == None: 141 | latestTimestamp = 0 142 | 143 | saveLastTimestamp(latestTimestamp,'last_article_timestamp.txt') 144 | print('上次更新到:%s' % getDate(latestTimestamp)) 145 | articlePage = 1 146 | 147 | while True: 148 | getArticle(articlePage,latestTimestamp,conn) 149 | articlePage = articlePage + 1 150 | sleepTimes(3) 151 | 152 | -------------------------------------------------------------------------------- /auto.bat: -------------------------------------------------------------------------------- 1 | cd D:\dev\python\sinaCrawler 2 | python post.py 3 | python article.py 4 | pause -------------------------------------------------------------------------------- /config.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | config.py 6 | ~~~~~~~~~~~~~~~~~ 7 | Constants need in crawler 8 | """ 9 | # Header 10 | headers = { 11 | 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36' 12 | } 13 | # Header for crawl article 14 | # articleHeaders = { 15 | # 'Cookie':r'_T_WM=0b13657a0903c215891afe5a7a4012cd; ALF=1532181429; WEIBOCN_FROM=1110005030; SCF=Att_NsRwCo9sMXbYndJPt4Sl30epTVZCzDk3yaiNUg2GefeRMdqshooy58qaUZpwaWpYpaHzKl4SOntfxkgzstM.; SUB=_2A252L96_DeRhGedO6lcV8yvLzziIHXVV0-L3rDV6PUJbktANLXTVkW1NIy84ODGyaWMsczoLwB7knUvQ3qWd91vF; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5dDAfB1DujZzmLzymi6i1K5JpX5K-hUgL.Fo27eK-Xe0-NShB2dJLoIpjLxKnLB.qL1-zLxKqLB-BLBK-LxKnLB--LBo5t; SUHB=0au2DNPXsvoq0w; SSOLoginState=1529589487; MLOGIN=1; M_WEIBOCN_PARAMS=luicode%3D10000011%26lfid%3D2310181496913734_-_longbloglist_original%26oid%3D3787648436993966%26uicode%3D10000370', 16 | # 'User-Agent':"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Mobile Safari/537.36" 17 | # } 18 | articleHeaders = { 19 | 'Cookie':r'_T_WM=bde86559938e533e578d8172691246fa; ALF=1533135809; WEIBOCN_FROM=1110005030; SCF=AmmfF3qnIlzy94enIcFLjnaUnAQUiWWCEQgCmuJzaXlJSE7YZyb3gRRsVQ0YI7bIewVscLQGHUkbpuIzhddVmKI.; SUB=_2A252Pk-2DeRhGedO6lcV8yvLzziIHXVVwVH-rDV6PUJbktAKLXH9kW1NIy84OHYpt7fpp7lbi4bvyC_LBonmjMHJ; SUBP=0033WrSXqPxfM725Ws9jqgMF55529P9D9W5dDAfB1DujZzmLzymi6i1K5JpX5K-hUgL.Fo27eK-Xe0-NShB2dJLoIpjLxKnLB.qL1-zLxKqLB-BLBK-LxKnLB--LBo5t; SUHB=0d4IP5HsLbH4R3; SSOLoginState=1530544102; MLOGIN=1; M_WEIBOCN_PARAMS=fid%3D1005051496913734%26uicode%3D10000011', 20 | 'User-Agent':"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Mobile Safari/537.36" 21 | } 22 | # URL format of Post list 23 | listUrlFormat = r'https://m.weibo.cn/api/container/getIndex?type=uid&value=1496913734&containerid=1076031496913734&page={}' 24 | 25 | # URL format of Post 26 | postUrlFormat = r'https://m.weibo.cn/statuses/extend?id={}' 27 | 28 | # URL format of Post comment 29 | commentUrlFormat = r'https://m.weibo.cn/api/comments/show?id={id}&page={page}' 30 | 31 | # URL format of Article list 32 | # articleListUrlFormat = r'https://m.weibo.cn/api/container/getIndex?containerid=2303190002_445_1496913734_WEIBO_ARTICLE_LIST_DETAIL&count=20&luicode=10000011&lfid=1005051496913734&type=uid&value=1496913734&page={}' 33 | articleListUrlFormat = r'https://m.weibo.cn/api/container/getIndex?containerid=2310181496913734_-_longbloglist_original&luicode=10000011&lfid=1005051496913734&page={}' 34 | 35 | # URL format of Article 36 | articleUrlFormat = r'https://media.weibo.cn/article?object_id={object_id}&id={id}' -------------------------------------------------------------------------------- /database.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | database.py 6 | ~~~~~~~~~~~~~~~~~ 7 | Encapsule some database operations in pymysql 8 | """ 9 | 10 | import pymysql 11 | 12 | def db_connector(): 13 | '''Create a database connector with your database config''' 14 | 15 | conn = pymysql.connect("localhost","root","root","weibo", use_unicode = True, charset="utf8mb4") 16 | return conn 17 | 18 | def insert_data(table_name,conn, **kw): 19 | '''Insert data into table''' 20 | 21 | # Concat SQL string which format like:"INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" 22 | sql = "INSERT INTO %s" % table_name 23 | sql += " (" 24 | tail_part = "VALUES (" 25 | value_list = [] 26 | 27 | for key,value in kw.items(): 28 | sql += "`" + key +"`," 29 | tail_part += "%s," 30 | value_list.append(value) 31 | 32 | sql = sql[:-1] 33 | sql += ") " 34 | 35 | tail_part = tail_part[:-1] 36 | tail_part += ")" 37 | 38 | # Need a tuple as parameter 39 | value_tuple = tuple(value_list) 40 | sql = sql + tail_part 41 | 42 | #Insert data into table 43 | conn.cursor().execute(sql,value_tuple) 44 | conn.commit() 45 | 46 | def selectData(conn,table,fieldnum): 47 | '''Select one record from table and return specify field value 48 | :fieldnum:the index of the field,start from zero 49 | ''' 50 | sql = "SELECT * FROM `%s` order by add_time desc limit 1" % table 51 | cur = conn.cursor() 52 | cur.execute(sql) 53 | for r in cur: 54 | return r[fieldnum] 55 | 56 | def closeConn(conn): 57 | '''close the connection''' 58 | conn.close() 59 | 60 | -------------------------------------------------------------------------------- /gadget.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | gadget.py 6 | ~~~~~~~~~~~~~~~~~ 7 | Some small tools 8 | """ 9 | 10 | import time 11 | import datetime 12 | import os 13 | 14 | def getTimestamp(text): 15 | '''Get timestamp from giving text''' 16 | 17 | if '刚刚' in text: 18 | return int(time.time()) 19 | elif '小时' in text: 20 | text = text.replace('小时前', '').strip() 21 | seconds = int(text)*3600 22 | return int(time.time()) - seconds 23 | elif '分钟' in text: 24 | text = text.replace('分钟前', '').strip() 25 | seconds = int(text)*60 26 | return int(time.time()) - seconds 27 | elif '昨天' in text: 28 | text = text.replace('昨天','').strip() 29 | timeArray = text.split(':') 30 | today = datetime.date.today() 31 | yesterday = today - datetime.timedelta(days = 1) 32 | timeStruct = time.strptime(str(yesterday),'%Y-%m-%d') 33 | timestamp = int(time.mktime(timeStruct)) 34 | timestamp = timestamp + int(timeArray[0]) * 3600 + int(timeArray[1]) * 60 35 | return timestamp 36 | else: 37 | if text.count('-') == 1: 38 | text = '2018-' + text 39 | if ':' in text and ' ' in text: 40 | timeStruct = time.strptime(text,'%Y-%m-%d %H:%M') 41 | else: 42 | timeStruct = time.strptime(text,'%Y-%m-%d') 43 | timestamp = int(time.mktime(timeStruct)) 44 | return timestamp 45 | 46 | def getDate(timestamp): 47 | '''Transform timestamp to date''' 48 | 49 | timeLocal = time.localtime(timestamp) 50 | dt = time.strftime("%Y-%m-%d %H:%M:%S",timeLocal) 51 | return dt 52 | 53 | def sleepTimes(num): 54 | time.sleep(num) 55 | 56 | def saveLastTimestamp(timestamp,filename): 57 | if not os.path.exists('log'): 58 | os.mkdir('log') 59 | with open('log/'+filename,'a',encoding='utf-8') as f: 60 | f.write('保存时间:'+str(datetime.datetime.now())+'\t开始时间戳:'+str(timestamp)+'\n') 61 | f.close() 62 | 63 | def saveFailId(id,title): 64 | if not os.path.exists('log'): 65 | os.mkdir('log') 66 | with open('log/weibo_article_fail_id.txt','a',encoding='utf-8') as f: 67 | f.write(title+'\t'+str(id)+'\n') 68 | f.close() 69 | -------------------------------------------------------------------------------- /post.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | """ 5 | post.py 6 | ~~~~~~~~~~~~~~~~~ 7 | Crawl post content 8 | """ 9 | import requests 10 | import json 11 | from bs4 import BeautifulSoup 12 | from config import * 13 | from database import * 14 | from gadget import * 15 | 16 | def getContent(page,latestTimestamp,conn): 17 | '''get post content and save in database''' 18 | 19 | # convert timestamp to date format 20 | timeLocal = getDate(latestTimestamp) 21 | print("=====开始抓取时间[%s]之后的微博=====" % timeLocal) 22 | print("=====开始抓取第%s页之后的微博=====" % page) 23 | url = listUrlFormat.format(page) 24 | 25 | data = requests.get(url, headers = headers) 26 | data.encoding = 'utf-8' 27 | data = json.loads(data.text) 28 | 29 | # use to record fail time 30 | breakCount = 0 31 | # Process all post items 32 | for content in data['data']['cards']: 33 | if('mblog' in content.keys()): 34 | addTime = getTimestamp(content['mblog']['created_at']) 35 | print('添加时间%s' % addTime) 36 | 37 | # Crawl time between A and B,use: 38 | # if addTime > 1528905600 and addTime < 1529421596: 39 | # Crawl time after latest timestamp 40 | if addTime > latestTimestamp: 41 | print('POST ID: %s 开始抓取\n' % content['mblog']['id']) 42 | kwPost = {} 43 | kwPost['add_time'] = addTime 44 | kwPost['post_id'] = content['mblog']['id'] 45 | kwPost['attitudes_count'] = content['mblog']['attitudes_count'] 46 | kwPost['comments_count'] = content['mblog']['comments_count'] 47 | 48 | # if there is not long text, use the current text,otherwise get the long text 49 | if content['mblog']['isLongText'] == False: 50 | kwPost['content'] = content['mblog']['text'] 51 | else: 52 | kwPost['content'] = getLongTextContent(content['mblog']['id']) 53 | # if fail to get long text, just use the short one instead 54 | if kwPost['content'] == False: 55 | kwPost['content'] = content['mblog']['text'] 56 | # if has retweeted content, get it in the same way 57 | if 'retweeted_status' in content['mblog']: 58 | kwPost['retweet_id'] = content['mblog']['retweeted_status']['id'] 59 | # if there is not long text, use the current text,otherwise get the long text 60 | if content['mblog']['retweeted_status']['isLongText'] == False: 61 | kwPost['retweet_content'] = content['mblog']['retweeted_status']['text'] 62 | else: 63 | kwPost['retweet_content'] = getLongTextContent(content['mblog']['retweeted_status']['id']) 64 | # if fail to get long text, use the short one instead 65 | if kwPost['retweet_content'] == False: 66 | kwPost['retweet_content'] = content['mblog']['retweeted_status']['text'] 67 | 68 | # Insert post data into database 69 | insert_data('wb_mzm_post',conn,**kwPost) 70 | print('POST ID: %s 写入成功\n' % kwPost['post_id']) 71 | 72 | # Start getting comments of post 73 | for data in getComment(kwPost['post_id'],0): 74 | if data: 75 | kwComment = {} 76 | kwComment['post_id'] = kwPost['post_id'] 77 | kwComment['comment_id'] = data[0] 78 | kwComment['like_count'] = data[1] 79 | kwComment['add_time'] = data[2] 80 | kwComment['comment_user_id'] = data[3] 81 | kwComment['comment_user_name'] = data[4] 82 | kwComment['user_photo'] = data[5] 83 | kwComment['user_profile'] = data[6] 84 | kwComment['text'] = data[7] 85 | kwComment['reply_text'] = data[8] 86 | insert_data('wb_mzm_comment', conn, **kwComment) 87 | print('POST ID:%s 的评论写入完毕\n' % kwPost['post_id']) 88 | else: 89 | print('已抓取,不写入') 90 | breakCount = breakCount + 1 91 | # if reach the limit fail times,stop 92 | if breakCount == 5: 93 | # close database connection 94 | closeConn(conn) 95 | print('已经抓取完毕,程序结束...') 96 | exit() 97 | 98 | print('=====第%s页抓取完毕=====\n' % page) 99 | 100 | def getLongTextContent(id): 101 | url = postUrlFormat.format(id) 102 | data = requests.get(url, headers = headers) 103 | if data and '打开微博客户端' not in data.text: 104 | data.encoding = 'utf-8' 105 | data = json.loads(data.text) 106 | return data['data']['longTextContent'] 107 | else: 108 | return False 109 | 110 | def getComment(id,page): 111 | '''get all comments of a post page by page recursively and return a generator''' 112 | url = commentUrlFormat.format(id = id, page = page) 113 | data = requests.get(url, headers = headers) 114 | data.encoding = 'utf-8' 115 | data = json.loads(data.text) 116 | # while return data normally 117 | while data['ok'] == 1 and 'data' in data.keys() and page < data['data']['max']: 118 | for content in data['data']['data']: 119 | addTime = getTimestamp(content['created_at']) 120 | # the comment has both replay text and text 121 | if 'reply_text' in content.keys() and 'text' in content.keys(): 122 | yield [content['id'], content['like_counts'], addTime, content['user']['id'], content['user']['screen_name'], content['user']['profile_image_url'], content['user']['profile_url'], content['text'], content['reply_text']] 123 | # the comment only has reply text 124 | elif 'reply_text' in content.keys() and 'text' not in content.keys(): 125 | yield [content['id'], content['like_counts'], addTime, content['user']['id'], content['user']['screen_name'], content['user']['profile_image_url'], content['user']['profile_url'], '', content['reply_text']] 126 | # the comment only has text 127 | elif 'reply_text' not in content.keys() and 'text' in content.keys(): 128 | yield [content['id'], content['like_counts'], addTime, content['user']['id'], content['user']['screen_name'], content['user']['profile_image_url'], content['user']['profile_url'], content['text'], ''] 129 | # print('抓取评论第%s页\n' % page) 130 | page = page + 1 131 | url = commentUrlFormat.format(id = id, page = page) 132 | data = requests.get(url, headers = headers) 133 | data.encoding = 'utf-8' 134 | data = json.loads(data.text) 135 | 136 | if __name__ == '__main__': 137 | conn = db_connector() 138 | latestTimestamp = selectData(conn,'wb_mzm_post',3) 139 | if latestTimestamp == None: 140 | latestTimestamp = 0 141 | saveLastTimestamp(latestTimestamp,'last_post_timestamp.txt') 142 | print('上次更新到:%s' % getDate(latestTimestamp)) 143 | postPage = 1 144 | # the program would exit while all latest posts are crawled,the break point locate in getContent() 145 | while True: 146 | getContent(postPage,latestTimestamp,conn) 147 | postPage = postPage + 1 148 | sleepTimes(3) 149 | -------------------------------------------------------------------------------- /sina.sql: -------------------------------------------------------------------------------- 1 | CREATE DATABASE IF NOT EXISTS `weibo`; 2 | USE `weibo`; 3 | 4 | CREATE TABLE IF NOT EXISTS `wb_mzm_article` ( 5 | `id` bigint(16) unsigned NOT NULL AUTO_INCREMENT, 6 | `article_id` varchar(30) NOT NULL, 7 | `title` varchar(150) CHARACTER SET utf8 NOT NULL, 8 | `content` text CHARACTER SET utf8 NOT NULL, 9 | `add_time` int(10) NOT NULL, 10 | PRIMARY KEY (`id`) 11 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 12 | 13 | CREATE TABLE IF NOT EXISTS `wb_mzm_comment` ( 14 | `id` bigint(16) unsigned NOT NULL AUTO_INCREMENT, 15 | `post_id` bigint(16) unsigned NOT NULL, 16 | `comment_id` bigint(16) unsigned NOT NULL, 17 | `comment_user_id` bigint(16) unsigned NOT NULL, 18 | `comment_user_name` varchar(50) CHARACTER SET utf8 DEFAULT NULL, 19 | `text` text, 20 | `reply_text` text, 21 | `user_photo` text CHARACTER SET utf8, 22 | `user_profile` text CHARACTER SET utf8, 23 | `add_time` int(10) DEFAULT NULL, 24 | `like_count` int(10) DEFAULT NULL, 25 | PRIMARY KEY (`id`) 26 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 27 | 28 | CREATE TABLE IF NOT EXISTS `wb_mzm_post` ( 29 | `id` bigint(16) unsigned NOT NULL AUTO_INCREMENT, 30 | `post_id` bigint(16) unsigned NOT NULL, 31 | `content` mediumtext NOT NULL, 32 | `add_time` int(10) DEFAULT NULL, 33 | `attitudes_count` int(10) DEFAULT NULL, 34 | `comments_count` int(10) DEFAULT NULL, 35 | `retweet_content` mediumtext, 36 | `retweet_id` bigint(16) DEFAULT NULL, 37 | PRIMARY KEY (`id`) 38 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 39 | --------------------------------------------------------------------------------