首页 / PYTHON / python爬取豆瓣新书清单
python爬取豆瓣新书清单
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python爬取豆瓣新书清单,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1732字,纯文字阅读大概需要3分钟。
内容图文
- 使用python3的requests库快速获取豆瓣图书推荐的新书清单,并保存书籍信息和图书缩略图图片到本地
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author:Aiker Zhao
@file:douban3.py
@time:上午10:34
"""
import json
import os
import re
from multiprocessing import Pool
import requests
from requests.exceptions import RequestException
dir = 'z:\\douban\\'
def get_web(url):
try:
rq = requests.get(url)
if rq.status_code == 200:
return rq.text
return None
except RequestException:
return None
def parse_web(html):
pattern = re.compile('<li\sclass="">.*?cover".*?href="(.*?)"\stitle="(.*?)".*?img\***c="(.*?)"' +
'.*?class="author">(.*?)<.*?year">(.*?)<.*?publisher">(.*?)<.*?</li>', re.S)
results = re.findall(pattern, html)
# print(results)
for i in results:
# url, title, img, author, yeah, publisher = i
# author = re.sub('\s', '', author)
# yeah = re.sub('\s', '', yeah)
# publisher = re.sub('\s', '', publisher)
# print(url, title, img, author, yeah, publisher)
yield {
'title': i[1],
'url': i[0],
'img': i[2],
'author': i[3].strip(),
'yeah': i[4].strip(),
'publisher': i[5].strip()
}
# print(url, title, img, author, yeah, publisher)
# return img,title
def save_image(title, img):
images = dir + title + '.jpg'
if os.path.exists(images):
pass
else:
with open(images, 'wb') as f:
f.write(requests.get(img).content)
f.close()
def save_info(content):
info = dir + 'info.txt'
with open(info, 'a', encoding='utf-8') as fd: #防止出现ascII
fd.write(json.dumps(content, ensure_ascii=False) + '\n') ##防止出现ascII
fd.close()
def main():
url = 'https://book.douban.com/'
html = get_web(url)
# parse_web(html)
for i in parse_web(html):
print(i)
save_info(i)
save_image(i.get('title'), i.get('img'))
if __name__ == '__main__':
main()
- 心得:
- 需要注意正则的匹配规则的准确度,否则会没有响应,或者无限超时
内容总结
以上是互联网集市为您收集整理的python爬取豆瓣新书清单全部内容,希望文章能够帮你解决python爬取豆瓣新书清单所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。