
正文
python 爬取36kr 7x24h快讯
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
url为https://36kr.com/newsflashes,抓包后发现第一次的新闻内容就是包含在<script>var props={}></script>标签中,具体的是在props中的key为newsflashList|newsflash的列表中紧着我又让页面多加载了一些,发现此时请求地址有了些变化,此时返回的内容是json字符串了
仔细研究下请求中的bid其实和返回的items中的最后一个id是相同的,这意味着我们可以第一次请求https://36kr.com/newsflashes,解析其中的props标签,然后获得最后一个id,接下来构造新的url时就可以采用形如https://36kr.com/api/newsflash?b_id=160678&per_page=20&_=1553412863268格式的地址了,测试发现只需要https://36kr.com/api/newsflash?b_id=160678&per_page=20就可以了,这个地址其实是多了层"api",测试时发现构造这种https://36kr.com/newsflashes?b_id=160680&per_page=20这个地址没有那层"api",所以返回的也是html,解析props标签同样可以获得数据
好了,综上我们有了两种思路,第一种是请求https://36kr.com/newsflashes,正则解析props.然后获得id,构造返回值为json字符串的url,第二种也是请求https://36kr.com/newsflashes,解析props.然后获得id,
构造返回html内容的url,之后也是使用正则解析props标签,但实际测试时这种效率有点低,因为大规模的使用了正则匹配,
所以我使用了第一种方式,此外使用第一种方式我们可以指定per_page,虽然过大容易被封IP
# -*- coding: utf-8 -*-
# @author: Tele
# @Time : 2019/3/24 0024 下午 12:56
import re
import json
import requests
import os
from pprint import pprint class NewsFlashesSplider:
def __init__(self):
# "https://36kr.com/newsflashes?b_id={}&per_page=20"
self.url = "https://36kr.com/newsflashes"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36"
}
self.file_dir = "./newsflashes.txt" def parse_url(self):
response = requests.get(self.url, headers=self.headers)
ret = json.loads(response.content.decode())["data"]["items"] print(ret) size = len(ret)
last_id = int(ret[size - 1]["id"])
with open(self.file_dir, "a", encoding="utf-8") as file:
file.write(json.dumps(ret, ensure_ascii=False))
file.write("\r\n")
return size, last_id def run(self):
if os.path.exists(self.file_dir):
os.remove(self.file_dir)
print("文件已清空") # 第一次请求获得当前最新的新闻
response = requests.get(self.url, headers=self.headers)
result = re.compile("<script>var props=(.*),locationnal=").findall(response.content.decode())
ret = json.loads(result[0])["newsflashList|newsflash"] # 新闻个数,最后一个id
tuple_result = len(ret), int(ret[len(ret) - 1]["id"]) while True:
self.url = "https://36kr.com/api/newsflash?b_id={}&per_page=20".format(tuple_result[1])
tuple_result = self.parse_url()
if tuple_result[0] < 20:
break def main():
splider = NewsFlashesSplider()
splider.run() if __name__ == '__main__':
main()






