一键下载新华社图片新闻

新华社图片新闻的地址正确

http://sn.news.cn/2022-02/26/c_1128419282.htm

import requests
import bs4
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36 Edg/98.0.1108.62'}
def downimg(name,img):
h = requests.get(img,headers=headers)
with open(f'./{name}.jpg','wb') as f:
f.write(h.content)
def main(url):
h = requests.get(url,headers=headers)
print(h.status_code,h.url)
if h.status_code != 200:return h.status_code
h = bs4.BeautifulSoup(h.content.decode())
标题 = h.find(id='title').text
图片地址 = url[:29] + h.find(id="content").find('img').attrs['src']
downimg('1',图片地址)
txt = []
for i in h.find(id="content").findAll('p'):
if i.text == '':continue
txt.append(''.join(i.text.split()))
for u in range(2,10):
ur = url[:-4] + f'_{u}.htm'
h = requests.get(ur,headers=headers)
print(h.status_code,h.url)
if h.status_code != 200:
print('错误代码:',h.status_code)
return '错误代码'
h = bs4.BeautifulSoup(h.content.decode())
图片地址 = url[:29] + h.find(id="content").find('img').attrs['src']
downimg(f'{u}',图片地址)
for i in h.find(id="content").findAll('p'):
if i.text == '':continue
txt.append(''.join(i.text.split()))
#写入文件
with open('./新闻稿.txt','w') as f:
f.write(f'{list(set(txt))}')
if __name__=='__main__':
# url = input('新华社图片频道第一张地址:')
url = 'http://sn.news.cn/2022-02/26/c_1128419282.htm'
main(url)
posted @   幽见〆南山  阅读(170)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示