|

楼主 |
发表于 2017-12-18 10:04:10
|
显示全部楼层
本题的解法其实qwc3000已经写得非常好了,大家可以参考他的程序。
如果不想使用第三方库wkhtmltopdf,仅仅把爬取的网页保存为html文件其实也是可以的。但是显示效果没有pdf来的好。
但程序相对简单,附上核心程序,未添加定时爬取和多线程等功能,仅供参考。
- import requests
- from bs4 import BeautifulSoup
- url = 'https://daily.zhihu.com'
- head = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
- 'Accept-Encoding':'gzip, deflate, br',
- 'Accept-Language':'zh-CN,zh;q=0.9',
- 'Cache-Control':'max-age=0',
- 'Connection':'keep-alive',
- 'Host':'daily.zhihu.com',
- 'Upgrade-Insecure-Requests':'1',
- 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'}
-
- resp = requests.get(url, headers=head)
- bs = BeautifulSoup(resp.text, 'lxml')
- for item in bs.select('div.box'):
- tt = item.span.text.replace('\r','').replace('\n','')
- href = url+item.a.attrs['href']
- content = requests.get(href, headers=head).content
- with open(tt+'.html','wb') as html:
- html.write(content)
复制代码
基本上爬取的内容和图片都可以正常显示的,因为是html文件,还是需要联网条件下打开,离线的话,图片会显示不正常。离线推荐用wkhtmltopdf转换成pdf阅读。 |
|