Python多线程爬取豆瓣影评API接口
爬虫库
使用简单的requests库,这是一个阻塞的库,速度比较慢。
解析使用XPATH表达式
总体采用类的形式
多线程
使用concurrent.future并发模块,建立线程池,把future对象扔进去执行即可实现并发爬取效果
数据存储
使用PythonORMsqlalchemy保存到数据库,也可以使用自带的csv模块存在CSV中。
API接口
因为API接口存在数据保护情况,一个电影的每一个分类只能抓取前25页,全部评论、好评、中评、差评所有分类能爬100页,每页有20个数据,即最多为两千条数据。
因为时效性原因,不保证代码能爬到数据,只是给大家一个参考思路,上代码:
fromdatetimeimportdatetime
importrandom
importcsv
fromconcurrent.futuresimportThreadPoolExecutor,as_completed
fromlxmlimportetree
importpymysql
importrequests
frommodelsimportcreate_session,Comments
#随机UA
USERAGENT=[
'Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/535.1(KHTML,likeGecko)Chrome/14.0.835.163Safari/535.1',
'Mozilla/5.0(Macintosh;IntelMacOSX10_12_6)AppleWebKit/537.36(KHTML,likeGecko)Chrome/73.0.3683.103Safari/537.36',
'Mozilla/5.0(WindowsNT6.1;WOW64;rv:6.0)Gecko/20100101Firefox/6.0',
'Mozilla/5.0(WindowsNT6.1;WOW64)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50',
'Opera/9.80(WindowsNT6.1;U;zh-cn)Presto/2.9.168Version/11.50',
'Mozilla/5.0(Windows;U;WindowsNT6.1;)AppleWebKit/534.12(KHTML,likeGecko)Maxthon/3.0Safari/534.12'
]
classCommentFetcher:
headers={'User-Agent':''}
cookie=''
cookies={'cookie':cookie}
#cookie为登录后的cookie,需要自行复制
base_node='//div[@class="comment-item"]'
def__init__(self,movie_id,start,type=''):
'''
:type:全部评论:'',好评:h中评:m差评:l
:movie_id:影片的ID号
:start:开始的记录数,0-480
'''
self.movie_id=movie_id
self.start=start
self.type=type
self.url='https://movie.douban.com/subject/{id}/comments?start={start}&limit=20&sort=new_score\&status=P&percent_type={type}&comments_only=1'.format(
id=str(self.movie_id),
start=str(self.start),
type=self.type
)
#创建数据库连接
self.session=create_session()
#随机useragent
def_random_UA(self):
self.headers['User-Agent']=random.choice(USERAGENT)
#获取api接口,使用get方法,返回的数据为json数据,需要提取里面的HTML
def_get(self):
self._random_UA()
res=''
try:
res=requests.get(self.url,cookies=self.cookies,headers=self.headers)
res=res.json()['html']
exceptExceptionase:
print('IP被封,请使用代理IP')
print('正在获取{}开始的记录'.format(self.start))
returnres
def_parse(self):
res=self._get()
dom=etree.HTML(res)
#id号
self.id=dom.xpath(self.base_node+'/@data-cid')
#用户名
self.username=dom.xpath(self.base_node+'/div[@class="avatar"]/a/@title')
#用户连接
self.user_center=dom.xpath(self.base_node+'/div[@class="avatar"]/a/@href')
#点赞数
self.vote=dom.xpath(self.base_node+'//span[@class="votes"]/text()')
#星级
self.star=dom.xpath(self.base_node+'//span[contains(@class,"rating")]/@title')
#发表时间
self.time=dom.xpath(self.base_node+'//span[@class="comment-time"]/@title')
#评论内容所有span标签class名为short的节点文本
self.content=dom.xpath(self.base_node+'//span[@class="short"]/text()')
#保存到数据库
defsave_to_database(self):
self._parse()
foriinrange(len(self.id)):
try:
comment=Comments(
id=int(self.id[i]),
username=self.username[i],
user_center=self.user_center[i],
vote=int(self.vote[i]),
star=self.star[i],
time=datetime.strptime(self.time[i],'%Y-%m-%d%H:%M:%S'),
content=self.content[i]
)
self.session.add(comment)
self.session.commit()
return'finish'
exceptpymysql.err.IntegrityErrorase:
print('数据重复,不做任何处理')
exceptExceptionase:
#数据添加错误,回滚
self.session.rollback()
finally:
#关闭数据库连接
self.session.close()
#保存到csv
defsave_to_csv(self):
self._parse()
f=open('comment.csv','w',encoding='utf-8')
csv_in=csv.writer(f,dialect='excel')
foriinrange(len(self.id)):
csv_in.writerow([
int(self.id[i]),
self.username[i],
self.user_center[i],
int(self.vote[i]),
self.time[i],
self.content[i]
])
f.close()
if__name__=='__main__':
withThreadPoolExecutor(max_workers=4)asexecutor:
futures=[]
foriin['','h','m','l']:
forjinrange(25):
fetcher=CommentFetcher(movie_id=26266893,start=j*20,type=i)
futures.append(executor.submit(fetcher.save_to_csv))
forfinas_completed(futures):
try:
res=f.done()
ifres:
ret_data=f.result()
ifret_data=='finish':
print('{}成功保存数据'.format(str(f)))
exceptExceptionase:
f.cancel()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短