首页 文章 精选 留言 我的

精选列表

搜索[python],共10000篇文章
优秀的个人博客,低调大师

python爬取电影和美食数据实战

本文使用的是requests+正则来匹配网页内容,对于数据量较多的采用了多线程抓取的方法,共3个案例,分别是抓取猫眼电影TOP100榜单和淘票票正在热映的电影信息、以及美团的美食数据。这几个案例采用的方法大同小异。 1、首先选择想要爬取的网站 2、确定要用的模块,requests,json,re三个模块,如果想加快爬取速度可以加一个Pool 3、 网页请求,先得到整个页面,需要加一个headers来进行请求,否则会被网站拦截 4、格式化整个页面,通过patter的正则来匹配,找出我们需要的内容, 5、 获取数据,findall,然后通过yield将数据返回,yield 是一个类似 return 的关键字,迭代一次遇到yield时就返回yield后面(右边)的值 6、遍历获取到的数据 7、保存到相应的文档中 8、关闭文档, 9、提示数据保存成功。 一、爬取猫眼电影Top100榜单的数据 importrequests frommultiprocessing importPool fromrequests.exceptions importRequestException importre importjson def get_one_page(url): try: headers = { "user-agent": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36'} 11response = requests.get(url , headers=headers) ifresponse.status_code == 200: returnresponse.text return None exceptRequestException: return None def parse_one_page(html): pattern = re.compile( '<dd>.*?board-index.*?>(\d+)</i>.*?data-src="(.*?)".*?name"><a'+ '.*?>(.*?)</a>.*?star">(.*?)</p>.*?releasetime">(.*?)</p>'+ '.*?integer">(.*?)</i>.*?fraction">(.*?)</i>.*?</dd>' ,re.S) items =re.findall(pattern ,html) foritem initems: yield{ 'index':item[ 0] , 'image':item[ 1] , 'title':item[ 2] , 'actor':item[ 3].strip()[ 3:] , 'time': item[ 4].strip()[ 5:] , 'score': item[ 5] + item[ 6] } def write_to_file(content): with open( 'result.txt' , 'a' , encoding= 'utf-8') asf: f.write(json.dumps(content , ensure_ascii= False) + ' \n ') f.close() def main(offset): url = 'http://maoyan.com/board/4?offset='+ str(offset) html = get_one_page(url) foritem inparse_one_page(html): #print(item)write_to_file(item) if__name__ == '__main__': #for i in range(10): # main(i*10)pool = Pool() pool.map(main ,[i* 10 fori in range( 10)]) 结果:将爬取的数据存放到文本文件中, 因为我这边采用的是线程池爬取的,所以有时候是不按顺序进行存储的,如果采用非多线程方式,就会按照顺序进行存储。 二、爬取淘票票正在热映的电影 可以看到网页结构如下,我这边使用了正则匹配的方法进行查找: 代码如下: importrequests fromrequests.exceptions importRequestException importre importjson def get_one_page(url): try: headers={ "user-agent": 'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/62.0.3202.94Safari/537.36'} 11 response=requests.get(url , headers=headers) ifresponse.status_code== 200: returnresponse.text returnNone exceptRequestException: returnNone def parse_one_page(html): pattern=re.compile( '<divclass="movie-card-poster">.*?data-src="(.*?)".*?<spanclass="bt-l">(.*?)</span>.*?<spanclass="bt-r">(.*?)</span>.*?<divclass="movie-card-list">.*?<span>(.*?)</span>' + '.*?<span>(.*?)</span>.*?<span>(.*?)</span>.*?<span>(.*?)</span>.*?<span>(.*?)</span>.*?<span>(.*?)</span>' ,re.S) items=re.findall(pattern ,html) foritem initems: yield{ 'image':item[ 0] , 'title':item[ 1] , 'score':item[ 2] , 'director':item[ 3].strip()[ 3:] , 'actor':item[ 4].strip()[ 3:] , 'type':item[ 5].strip()[ 3:] , 'area':item[ 6].strip()[ 3:] , 'language':item[ 7].strip()[ 3:] , 'time':item[ 8].strip()[ 3:] } def write_to_file(content): with open( 'movie-hot.txt' , 'a' , encoding= 'utf-8') asf: f.write(json.dumps(content , ensure_ascii= False)+ ' \n ') f.close() def main(): url= 'https://www.taopiaopiao.com/showList.htm' html=get_one_page(url) foritem inparse_one_page(html): print(item) write_to_file(item) if__name__== '__main__': main() 结果: 三、爬取美团(深圳)美食店铺信息,评分大于4.0分的店铺 做为一名吃货,想知道我所在是城市的美食店,所以爬取评分较高的店铺信息: 美团的这个网页的不同之处在于,全部是通过js渲染生成的,所以我这边是拿到页面后,在js里面查找到的数据,然后用正则来匹配。 importrequests frommultiprocessing importPool fromrequests.exceptions importRequestException importre importjson """ author 朱培 title 爬取美团(深圳)美食店铺信息,评分大于4.0分的店铺 """ def get_one_page(url): try: headers={ "user-agent": 'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/62.0.3202.94Safari/537.36'} response=requests.get(url , headers=headers) ifresponse.status_code== 200: returnresponse.text returnNone exceptRequestException: returnNone def parse_one_page(html): pattern=re.compile( '"poiId":(.*?),"frontImg":"(.*?)","title":"(.*?)","avgScore":(.*?),"allCommentNum":(.*?)' + ',"address":"(.*?)","avgPrice":(.*?),' ,re.S) items=re.findall(pattern ,html) foritem initems: if float(item[ 3])>= 4.0: yield{ 'poiId':item[ 0] , 'frontImg':item[ 1] , 'title':item[ 2] , 'avgScore':item[ 3] , 'allCommentNum':item[ 4] , 'address':item[ 5] , 'avgPrice':item[ 6] } def write_to_file(content): with open( 'food-meituan.txt' , 'a' , encoding= 'utf-8') asf: f.write(json.dumps(content , ensure_ascii= False)+ ' \n ') f.close() def main(n): url= 'http://sz.meituan.com/meishi/pn'+ str(n)+ '/' html=get_one_page(url) foritem inparse_one_page(html): print(item) write_to_file(item) if__name__== '__main__': #foriinrange(32): # main(i) pool=Pool() pool.map(main ,[ 1 fori in range( 32)]) 结果如下: 对于后期,可以选择把这个数据落库,常用的可以放在mongodb或者mysql数据库中进行存储。

优秀的个人博客,低调大师

python:教学工具:随机点名提问答卷

说多都是泪,姑且这么办吧. import random as rd 人数=11 题数=30 已经提问过的人=[] 没有提问过的人=[] 提问日志=[] for i in range(人数): 没有提问过的人.append(i) for i in range(题数): if len(没有提问过的人)==0: 没有提问过的人=sorted(已经提问过的人.copy()) 已经提问过的人.clear() num=rd.randint(0,len(没有提问过的人)-1) #print(没有提问过的人[num]) 人=没有提问过的人.pop(num) 已经提问过的人.append(人) 提问日志.append(人) elif len(没有提问过的人)>0: num=rd.randint(0,len(没有提问过的人)-1) #print(没有提问过的人[num]) 人=没有提问过的人.pop(num) 已经提问过的人.append(人) 提问日志.append(人) print('提问序列如下:') print(提问日志) print(len(提问日志)) 标识符的汉语见谅吧,没办法,要开源给学生,毕竟英语不是这门课的核心考察能力

优秀的个人博客,低调大师

python:小心类实例的属性动态绑定机制

class Test: def __init__(self): self.__key='init' def get_key(self): return self.__key def set_key(self,key): self.__key=key if __name__ == '__main__': obj = Test() print(obj.get_key())#输出初始值init obj.set_key('通过set方法设置的值') print(obj.get_key())#输出set方法修改之后的值 obj.__key = 'Should not use in this way'#动态绑定上去的属性 print(obj.get_key())#类的实例私有属性的值 print(obj.__key) #注意这个地方↑其实输出的是动态绑定到实例obj上面的属性,不是类里面的私有属性!

优秀的个人博客,低调大师

Python基础系列-列表交集并集差集

版权声明:如需转载,请注明转载地址。 https://blog.csdn.net/oJohnny123/article/details/81979449 比如,现在有两个list类型: a = [1,2,3,4] b = [1,2,3] 一. 差集 很明显结果是[4],下面我们说一下具体方法。 ret_list = [item for item in a if item not in b] 还有一种方法 ret_list = list(set(a)^set(b)) 二. 并集 很明显结果是[1,2,3,4],下面是具体方法: ret_list = list(set(a).union(set(b))) 三. 交集 很明显结果是[1,2,3],下面是具体方法: ret_list = list((set(a).union(set(b)))^(set(a)^set(b)))

优秀的个人博客,低调大师

python骚操作,指定微信好友发送消息

指定好友发送消息 大家在测试的时候尽量使用微信小号 不要不改代码就测试 这里调用了金山词霸的每日一句,你也可以指定文字信息发送,七夕快到了,你懂得。 from threading import Timer from wxpy import * import requests bot = Bot()#连接微信,会出现一个登陆微信的二维码 def get_news(): '''获取金山词霸每日一句''' url = 'http://open.iciba.com/dsapi' r = requests.get(url) content = r.json()['content'] note = r.json()['note'] return content,note def send_news(): try: contents = get_news() my_friend =bot.friends().search(u'小明')[0]#这里是你微信好友的昵称 my_friend.send(contents[0]) my_friend.send(contents[1]) my_friend.send(u'来自自动回复') t = Timer(86400,send_news)#这里是一天发送一次,86400s = 24h t.start() except: my_friend = bot.friends().search('sixkery')[0]#这里是你的微信昵称 my_friend.send(u'今天消息发送失败了') if __name__ == '__main__': send_news()

优秀的个人博客,低调大师

Python基础 | pandas.dataframe 专题使用指南

1.选取行名、列名、值 2.以标签(行、列的名字)为索引选择数据—— x.loc[行标签,列标签] 3.以位置(第几行、第几列)为索引选择数据—— x.iloc[行位置,列位置] 4.同时根据标签和位置选择数据——x.ix[行,列] 5.选择连续的多行多列——切片起点索引:终点索引 这种用法叫做一个切片,指从起点索引到终点索引。看实际用法就懂了。如果起点索引省略代表从头开始,终点索引省略代表直到最后,都省略就代表全部了。切片在.loc、.iloc、.ix三种方法中都可以应用 由上例可见,当以位置为索引时,切片是不包括终点的,是左闭右开的。即第1列到第3列不是写作0:2而是0:3。 6.选择不连续的某几行或某几列 备注:当以标签名选取不连续的某几行的时候在这个例子中如df.loc['2016-02-02','2016-02-04',:]这样写会出

资源下载

更多资源
Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册