python 爬虫 正则表达式爬取猫眼电影top100榜
2018-08-07 21:47
489 查看
版权声明: https://blog.csdn.net/qq_34246164/article/details/81489230
思路分析,首先分析猫眼电影的top100榜的网页特点,然后根据网页信息编写用于匹配的正则表达式,然后提取对应的信息即可。
接下来是对存储文件的操作,将最终的结果存储在csv结果。因为在编写过程中,要试很多次,为了不要每次都手动删除文件,因此在程序运行开始之前判断文件是否已经存在,如果存在则删除,然后开始便开始爬取信息。代码如下:
[code]import re import requests import csv import os class MaoYan(): def __init__(self): self.url = "http://maoyan.com/board/4" self.fieldnames = ['index','title', 'actor','time','score'] self.file = 0 def file_del(self): files = os.listdir(os.getcwd()) #列出目录下的文件 for file in files: suffix = file.split('.')[-1] if suffix == 'csv': os.remove(file) print(file,"文件已经被删除") def file_cre(self): self.file = open('my.csv','a', newline='') self.writer = csv.DictWriter(self.file, fieldnames=self.fieldnames) self.writer.writeheader() def url_cre(self): for i in range(10): url_start = "http://maoyan.com/board/4?offset=" url = url_start + str(i*10) yield url def html_get(self): for url in self.url_cre(): r = requests.get(url) html = r.text yield html def html_parse(self): for html in self.html_get(): p2 = re.compile('<dd>.*?board-index.*?>(.*?)</i>.*?class="name".*?><a.*?>(.*?)</a>.*?"star".*?>(.*?)</p>.*?releasetime.*?>(.*?)</p>.*?integer.*?>(.*?)</i>.*?fraction.*?>(.*?)</i>.*?</dd>', re.S) items = re.findall(p2,html) for item in items: info = { 'index':item[0], 'title':item[1], 'actor':item[2].strip().split(':')[-1], 'time':item[3].split(':')[-1], 'score':item[4]+item[5], } print(info) self.save_to_csv(info) def save_to_csv(self,info): global writer if self.writer.writerow(info): print("保存成功") def file_close(self): self.file.close() #关闭文件 def main(self): self.file_del() #首先进行文件删除 self.file_cre() #创建文件 self.html_parse() #解析并存储 self.file_close() #关闭文件 if __name__ == "__main__": app = MaoYan() app.main()
阅读更多
相关文章推荐
- python正则表达式爬取猫眼电影top100
- python正则表达式简单爬虫入门+案例(爬取猫眼电影TOP榜)
- python爬虫实战:抓取猫眼电影TOP100存放到MongoDB中
- Python3实战——request+正则表达式:爬取猫眼电影TOP100榜
- Python爬虫之三:抓取猫眼电影TOP100
- requests+正则表达式爬猫眼电影TOP100
- python 爬虫抓取猫眼电影 top100 源码
- 利用requests和正则表达式re爬取猫眼电影top100,并下载图片
- python爬虫爬取猫眼电影top100
- Python爬虫-爬取猫眼电影Top100榜单
- Python 爬虫学习笔记之正则表达式
- python 3.x 爬虫基础---正则表达式
- 一个简单的python爬虫程序 爬取豆瓣热度Top100以内的电影信息
- Python爬虫实践(六):正则表达式(1)
- 零基础写python爬虫之神器正则表达式
- python 爬虫004-使用urllib2与正则表达式扒取糗事百科新鲜页首页帖子
- Python爬虫urllib2笔记(三)之使用正则表达式提取百度贴吧网页中的楼主发的图片
- python爬虫入门(2)re模块-正则表达式
- 模拟登陆CSDN -- Python爬虫练习之正则表达式和cookie
- 04 Python正则表达式 爬虫程序 变量的引用,浅拷贝,深拷贝 多线程 进程锁 数据库模块