首页 > 编程 > Python > 正文

Python实现的爬取豆瓣电影信息功能案例

2019-11-25 11:43:23
字体:
来源:转载
供稿:网友

本文实例讲述了Python实现的爬取豆瓣电影信息功能。分享给大家供大家参考,具体如下:

本案例的任务为,爬取豆瓣电影top250的电影信息(包括序号、电影名称、导演和主演、评分以及经典台词),并将信息作为字典形式保存进txt文件。这里只用到requests库,没有用到beautifulsoup库

step1:首先获取每一页的源代码,用requests.get函数获取,为了防止请求错误,使用try...except..

def getpage(url):  try:    res=requests.get(url)    if res.status_code==200:      return res.text    return None  except RequestException:    return None

step2:做每一页的网址解析,打开原网址https://movie.douban.com/top250?,查看网页源代码,可以看到每一个电影的源代码都是从<li>开始,在</li>处结束,写好正则表达式以后爬到的列表的每一条item都有五个元素,因此将其写成字典的形式,这里用到yield函数(关于yield函数的用法,廖老师的有一篇文章比较好懂https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/)

对单个网页的进行解析的代码如下:

def parsepage(html):  pat=re.compile('<li>.*?<em class="">(.*?)</em>.*?<img width="100" alt="(.*?)" src=.*?<p class="">'          +'(.*?)</p>.*?property="v:average">(.*?)</span>.*?<span class="inq">(.*?)</span>.*?</li>',re.S)  items=re.findall(pat,html)  for item in items:    yield{      'index':item[0],      'title':item[1],      'stars':item[2].strip(),      'score':item[3],      'concept':item[4]    }

下面的代码是将每一个item写入文件,这里encoding='utf-8' 和ensure_ascii=False都是使写入文件时中文能保持不变,json.dumps可以将(字典)对象转化成字符串(但前面要先import json),with open的第二个参数为a,表示每次写入时,是往后追加(续接),而不是后一次写入将之前内容覆盖,/n是指要每一次写入一个item之后要换行。

def write_tofile(content):  with open('doubanfilms.txt','a',encoding='utf-8' ) as f:    f.write(json.dumps(content,ensure_ascii=False)+'/n')    f.close()

最后,需要用循环语句将每一页(共10页)内容都进行以上操作。这里,第二页的网址就是在第一页的url上加上一个start=25, 第三页是加上start=50,也就是每一页的start=为25*i。最后一段代码如下:

def main():  url="https://movie.douban.com/top250?"  for i in range(0,9):    url_i=url+'start='+str(25*i)    html_i=getpage(url_i)    for item in parsepage(html_i):      print(item)      write_tofile(item)if __name__ == '__main__':  main()

当然,这一段代码还有一种写法:

def main(start):  url="https://movie.douban.com/top250?start="+str(start)  html=getpage(url)  for item in parsepage(html):    print(item)    write_tofile(item)if __name__ == '__main__':  for i in range(10):    main(i*10)

如果想让你的程序跑的更快,可以用多线程爬虫(当然这里其实没有必要):

#在最开始加载Pool包from multiprocessing import Pool#最后的执行段改为:if __name__ == '__main__':  for i in range(10):    main(i*10)  pool=Pool() #在循环外写  pool.map(main,[i*10 for i in range (10)])

更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表