Python应用:获取网页内容
我把科学60秒音频放到喜马拉雅上听,并整理相应的文本每篇一个Markdown文件,以便做成EPUB电子书放阅读器里看http://git.oschina.net/freesand/eBook_60-SecondScience
普通操作是打开每个网页复制粘贴
可以用以下程序自动化处理# get60sScience.py 获取科学60秒播客首页的所有文章并写入文件
import requests # 下载网络资源的第三方库
import bs4 # 提取网页内容的第三方库beautifulsoup4
url = 'https://www.scientificamerican.com/podcast/60-second-science/'
path = 'D:\\Test\\60sScience\\'
# 获取首页
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text, 'html.parser')
# 获取所有文章链接(头条+列表)
elems = soup.select('.podcasts-header__title > a')
elems += soup.select('.podcasts-listing__title > a')
# 遍历所有文章链接
for i in range(len(elems)):
print('处理网页:' + str(i))
# 获取文章页
page = requests.get(elems.get('href'))
page.raise_for_status()
pageSoup = bs4.BeautifulSoup(page.text, 'html.parser')
# 创建文件并写入内容(MD格式)
pageFile = open(path + str(i) + '.md', 'wb')
# 标题
c = pageSoup.select('.podcasts-header__title')
pageFile.write(('\n# \n' + c.text + '\n').encode(encoding="utf-8"))
# 日期
c = pageSoup.select('li')
pageFile.write((c.text + '\n').encode(encoding="utf-8"))
# 摘要
c = pageSoup.select('.article-text > p')
pageFile.write((c.text).encode(encoding="utf-8"))
# 正文
c = pageSoup.select('.transcript__inner > p')
for j in range(len(c) - 1):
pageFile.write(('\n\n' + c.text).encode(encoding="utf-8"))
pageFile.close()
print('完工!') 还可以自动下载相应mp3文件,但网页上的文件名永远是podcast.mp3,似乎只有手工下才能以原文件名保存。用python获取原文件名的办法待研究:xzlh
页:
[1]