Target:爬取每本书的短评,并为文本分析做准备
- my_functions.py 用于自定义函数
from urllib import request
import ssl
import re
import os
context = ssl._create_unverified_context() # 创建上下文,用于访问网页的ssl验证
def make_path(p):
'''
该函数用于创建文件夹
若不存在该文件夹 则创建
若存在 即删除
'''
if not os.path.exists(p):
os.makedirs(p)
else:
os.rmdir(p)
return p+'/'
def crawl(url): #此处的url对应每本书的网页
# try:
page = request.urlopen(url,context=context,timeout=5)
html = page.read().decode('utf-8')
return html
#从每个类别的网页获取书的id号 构成获取评论的url
def get_book_id_web(html_file):
'''
此处的参数html_file是已经保存的五个类别的html网页
返回值是一个字典,key是书的id,value是对应的短评网址url
'''
url="https://book.douban.com/subject/"
book_web={}
p=r'(subject/)([0-9]+)(/" title=)'
book=re.findall(p,html_file)
for i in book:
s=url+i[1]+'/comments/hot?p='
book_web[i[1]]=s
return book_web
def get_comment(book_html,text_name):
'''
参数中的book_html是每一页短评url解析以后的网页,每本书共需要获取5页短评,即100条
id_no是对应的书号,用于创建每本书评论的tx

本文档记录了使用Python3爬取豆瓣各类书籍短评的过程,每本书的短评被保存为TXT文件,每个文件包含最多10页评论。通过自定义函数my_functions.py和主要爬虫脚本crawl_data.py实现数据抓取,爬取结果按书籍类别组织,为后续的数据分析和文本分析提供基础数据。
559

被折叠的 条评论
为什么被折叠?



