博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用requests模块爬取豆瓣电影top50数据
阅读量:3950 次
发布时间:2019-05-24

本文共 1476 字,大约阅读时间需要 4 分钟。

来上代码

import requestsimport reimport jsonimport time# 获取一页的数据def get_one_page(url):    headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; U; Mac OS X Mach-O; en-US; rv:2.0a) Gecko/20040614 Firefox/3.0.0 " } response = requests.get(url, headers=headers) if response.status_code == 200: return response.text return None#def main(offset): url = "https://maoyan.com/board/4?offset=" + str(offset) html = get_one_page(url) for item in parse_one_page(html): print(html) write_to_file(item)#def parse_one_page(html): pattern = re.compile( '
.*?board-index.*?>(.*?).*?data-src="(.*?)".*?name.*?a.*?>(.*?).*?star.*?>(.*?)

.*?releasetime.*?>(.*?)

.*?integer.*?>(.*?).*?fraction.*?>(.*?).*?
', re.S ) items = re.findall(pattern, html) print(items) for item in items: yield {
'index': item[0], 'image': item[1], 'title': item[2].strip(), 'actor': item[3].strip()[3:] if len(item[3]) > 3 else '', 'time': item[4].strip()[5:] if len(item[4]) > 5 else '', 'score': item[5].strip() + item[6].strip() }def write_to_file(content): with open('result.txt', 'a', encoding='utf-8') as f: print(type(json.dumps(content))) f.write(json.dumps(content, ensure_ascii=False) + '\n')if __name__ == '__main__': for i in range(10): main(offset=i * 10) time.sleep(1)

可以关注微信公众号:幽灵邀请函 获取更多学习资源

转载地址:http://xnuzi.baihongyu.com/

你可能感兴趣的文章
通过等待键盘输入让程序等待外部条件改变
查看>>
通过限制循环次数来避免死循环
查看>>
ADO连接字符串
查看>>
字符数组的位置决定程序能否成功执行--不明白
查看>>
拷贝代码时没有仔细检查,导致误修改了函数参数
查看>>
MySQL批量导入数据SQL语句(CSV数据文件格式)
查看>>
ADO连接Oracle
查看>>
遍历Windows系统中所有进程的名字(*.exe)
查看>>
进程看门狗
查看>>
线程看门狗
查看>>
调试代码的宏定义
查看>>
创建、重命名文件
查看>>
文件大小保护
查看>>
删除指定目录下所有文件及目录
查看>>
XDR-从文件空间解码整数
查看>>
XDR-.x文件的简单使用
查看>>
XDR-枚举的试用
查看>>
使用CppSQLite3访问SQLite数据库
查看>>
第一个boost程序---timer的使用
查看>>
使用boost asio库实现字节数可控的CS通信
查看>>