设为首页收藏本站

塞爱维(CIV)文明联盟

 找回密码
 注册
查看: 2748|回复: 1

[已解决] Python应用:获取网页内容

[复制链接]
发表于 2017-2-6 17:11:22 | 显示全部楼层 |阅读模式
我把科学60秒音频放到喜马拉雅上听,并整理相应的文本每篇一个Markdown文件,以便做成EPUB电子书放阅读器里看
http://git.oschina.net/freesand/eBook_60-SecondScience
普通操作是打开每个网页复制粘贴
可以用以下程序自动化处理
  1. # get60sScience.py 获取科学60秒播客首页的所有文章并写入文件
  2. import requests # 下载网络资源的第三方库
  3. import bs4 # 提取网页内容的第三方库beautifulsoup4

  4. url = 'https://www.scientificamerican.com/podcast/60-second-science/'
  5. path = 'D:\\Test\\60sScience\\'
  6. # 获取首页
  7. res = requests.get(url)
  8. res.raise_for_status()
  9. soup = bs4.BeautifulSoup(res.text, 'html.parser')
  10. # 获取所有文章链接(头条+列表)
  11. elems = soup.select('.podcasts-header__title > a')
  12. elems += soup.select('.podcasts-listing__title > a')
  13. # 遍历所有文章链接
  14. for i in range(len(elems)):
  15.     print('处理网页:' + str(i))
  16.     # 获取文章页
  17.     page = requests.get(elems[i].get('href'))
  18.     page.raise_for_status()
  19.     pageSoup = bs4.BeautifulSoup(page.text, 'html.parser')
  20.     # 创建文件并写入内容(MD格式)
  21.     pageFile = open(path + str(i) + '.md', 'wb')
  22.     # 标题
  23.     c = pageSoup.select('.podcasts-header__title')
  24.     pageFile.write(('\n# \n' + c[0].text + '  \n').encode(encoding="utf-8"))
  25.     # 日期
  26.     c = pageSoup.select('li[class="meta-list__item"]')
  27.     pageFile.write((c[0].text + '  \n').encode(encoding="utf-8"))
  28.     # 摘要
  29.     c = pageSoup.select('.article-text > p')
  30.     pageFile.write((c[0].text).encode(encoding="utf-8"))
  31.     # 正文
  32.     c = pageSoup.select('.transcript__inner > p')
  33.     for j in range(len(c) - 1):
  34.         pageFile.write(('\n\n' + c[j].text).encode(encoding="utf-8"))
  35.     pageFile.close()
  36. print('完工!')
复制代码
 楼主| 发表于 2017-2-6 17:18:52 | 显示全部楼层
还可以自动下载相应mp3文件,但网页上的文件名永远是podcast.mp3,似乎只有手工下才能以原文件名保存。用python获取原文件名的办法待研究
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|塞爱维(CIV)文明联盟    

GMT+8, 2024-3-29 22:24

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表