zoukankan      html  css  js  c++  java
  • selenium自动化方式爬取豆瓣热门电影

    爬取的代码如下:

    from selenium import webdriver
    from bs4 import BeautifulSoup
    import time
    #发送请求,获取响应
    def get_PageItem():
    	# 准备url
    	url='https://movie.douban.com/chart'
    	#创建一个浏览器对象
    	driver=webdriver.Chrome()
    	#发送请求
    	driver.get(url)
    	#print(driver.page_source)
    	page_code=BeautifulSoup(driver.page_source,"lxml")
    	#print(page_code)
    	#获取所有的inden类下面的所有table标签
    	items=page_code.select('.indent table')
    	return items
    
    
    def start():
    	"""启动程序"""
    	#获取当前时间
    	start_time=time.time()
    	#接收table标签
    	items=get_PageItem()
    	print("用时:",time.time()-start_time,"秒")
    	for item in items:
    		#查找电影标题 找到P12的div里面的a标签
    		name1=item.select("div.pl2 a")[0].text #也可以写成:name=item.select(".p12 a")[0].text
    		name2=name1.replace(" ","").replace("
    ","")
    		#获取演员列表,上映时间和电影类型
    		time_person=item.select(".pl")[0].text
    		#获取评价人数
    		num=item.select("span.pl")[0].text
    		#获取评分
    		score=item.select("span.rating_nums")[0].text
    		get_star(score)
    		with open("a.txt",'a',encoding = 'utf-8')as f:#使用with open在使用完成后会直接进行关闭,而直接使用open在使用完成后需要进行关闭,否则会占用内存
    			f.write("%s
    %s
    %s
    %s
    "%
    			        ("电影名称:%s"%name2,
    			         "演员列表:%s"%time_person,
    			         "评分和人数%s%s%s"%(get_star(score),score,num),
    			         "*"*200))
    
    #根据评分显示星星数量
    def get_star(score):
    	#打印出score的数据类型,在python中只有相同的数据类型才能进行乘法和除法操作。
    	#print(type(score))#打印出来,score是str类型,str类型是不能进行乘法和除法的操作
    	str1=''
    	for i in range(0,5):
    	# 	# 把score进行强转,转成float类型
    		if int(float(score)/2 )>i:
    			str1+="★"
    		else:
    			str1 += "☆"
    	return str1
    
    start()
    

      执行代码后,在a.txt文档中存放爬取的内容如下:

  • 相关阅读:
    源码安装extundelete以及对遇到问题的解决
    centos 连不上网
    memcache 永久数据被踢
    svn 分支
    HTML5 中已经可以用 Ajax 上传文件了,而且代码非常简单,借助 FormData 类即可发送文件数据。
    sublime安装DocBlockr注释插件
    rsync 无密码 传输
    滚动条滑到底部,加载更多
    svn 同步脚本
    蒲公英[分块]
  • 原文地址:https://www.cnblogs.com/benpao1314/p/11268540.html
Copyright © 2011-2022 走看看