突然看到一篇“你需要知道的隔夜全球要闻”,忍不住写个爬虫把它爬下来每天看看。
WX20230314-205640.png (205.56 KB, 下载次数: 0)
下载附件
2023-3-14 20:57 上传
第一步 找到通用接口
WX20230314-205134.png (506.92 KB, 下载次数: 0)
下载附件
2023-3-14 20:59 上传
WX20230314-205150.png (406.33 KB, 下载次数: 0)
下载附件
2023-3-14 20:59 上传
WX20230314-205208.png (466.16 KB, 下载次数: 0)
下载附件
2023-3-14 21:00 上传
第二步 测试接口
WX20230314-205327.png (290.33 KB, 下载次数: 0)
下载附件
2023-3-14 21:00 上传
第三步 尝试编写代码,反复测试
[Python] 纯文本查看 复制代码import requests
import json
import re
import time
from lxml import etree
if __name__ == '__main__':
url = 'https://www.cls.cn/api/sw?app=CailianpressWeb&os=web&sv=7.7.5&sign=bf0f367462d8cd70917ba5eab3853bce'
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0"}
data = {"type":"telegram","keyword":"你需要知道的隔夜全球要闻","page":0,"rn":20,"os":"web","sv":"7.7.5","app":"CailianpressWeb"}
response = requests.post(url=url,headers=headers,data=data)
news = json.loads(response.text)['data']['telegram']['data'][0]['descr']
timeStamp = json.loads(response.text)['data']['telegram']['data'][0]['time']
timeArray = time.localtime(timeStamp)
formatTime = time.strftime("%Y年%m月%d日", timeArray)
news = re.split(r'\d+、',news)
title = ''.join(etree.HTML(news[0]).xpath('//text()'))[1:-2]
print(formatTime,title)
for i in range(1, len(news)):
new = '%s、%s'%(i,news)
print(new)
WX20230314-204801.png (295.92 KB, 下载次数: 0)
下载附件
2023-3-14 21:04 上传
存在问题,本想通过正则表达式在"。数字、"数字前面通过正则替换内容替换新增换行,没想到输出的时候数字被\d+替换了。
感谢大神@Arcticlyc指点,优化正则替换。
如有不足,欢迎大家提出意见。
[Python] 纯文本查看 复制代码import requests
import json
import re
import time
from lxml import etree
if __name__ == '__main__':
url = 'https://www.cls.cn/api/sw?app=CailianpressWeb&os=web&sv=7.7.5&sign=bf0f367462d8cd70917ba5eab3853bce'
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/110.0"}
data = {"type":"telegram","keyword":"你需要知道的隔夜全球要闻","page":0,"rn":20,"os":"web","sv":"7.7.5","app":"CailianpressWeb"}
response = requests.post(url=url,headers=headers,data=data)
news = json.loads(response.text)['data']['telegram']['data'][0]['descr']
timeStamp = json.loads(response.text)['data']['telegram']['data'][0]['time']
timeArray = time.localtime(timeStamp)
formatTime = time.strftime("%Y年%m月%d日", timeArray)
news = re.sub(r'(\d+、)', r'\n\1', news)
formatNews = ''.join(etree.HTML(news).xpath('//text()'))
print(formatTime,formatNews)
WX20230314-230214.png (300.55 KB, 下载次数: 0)
下载附件
2023-3-14 23:02 上传