Python3 css选择器实战(二):爬取猫眼电影网

举报
悦来客栈的老板 发表于 2020/12/28 23:59:28 2020/12/28
【摘要】 #coding=utf-8import reimport timeimport requestsfrom requests.exceptions import RequestExceptionfrom bs4 import BeautifulSoupfrom prettytable import PrettyTable def getHtml(url): try: head...

  
  1. #coding=utf-8
  2. import re
  3. import time
  4. import requests
  5. from requests.exceptions import RequestException
  6. from bs4 import BeautifulSoup
  7. from prettytable import PrettyTable
  8. def getHtml(url):
  9. try:
  10. headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'}
  11. response = requests.get(url,headers = headers)
  12. if response.status_code == 200:
  13. return response.text
  14. return None
  15. except RequestException:
  16. return None
  17. if __name__=='__main__':
  18. lmovie = []
  19. lactor = []
  20. ltime = []
  21. lscore = []
  22. table = PrettyTable(['NO.','电影','主演','上映时间','猫眼评分'])
  23. index = 0
  24. for page in range(0,100,10):
  25. url = 'http://maoyan.com/board/4?offset={}'.format(page)
  26. Html = getHtml(url)
  27. if Html is None:
  28. contine
  29. Soup = BeautifulSoup(Html,'lxml')
  30. names = Soup.select('div.movie-item-info > p:nth-of-type(1)')
  31. for name in names:
  32. lmovie.append(name.text)
  33. actors = Soup.select('div.movie-item-info > p:nth-of-type(2)')
  34. for actor in actors:
  35. actor = actor.text
  36. actor = actor.split(':')[-1]
  37. lactor.append(actor.strip())
  38. releasetimes = Soup.select('div.movie-item-info > p:nth-of-type(3)')
  39. for retime in releasetimes:
  40. retime = retime.text
  41. retime = retime.split(':')[-1]
  42. ltime.append(retime)
  43. scores = Soup.select('p.score > i:nth-of-type(1)')
  44. for score in scores:
  45. lscore.append(score.text)
  46. frascores = Soup.select('p.score > i:nth-of-type(2)')
  47. for i in range(len(frascores)):
  48. lscore[index] += frascores[i].text
  49. index += 1
  50. time.sleep(1)
  51. for i in range(100):
  52. table.add_row([str(i+1),lmovie[i],lactor[i],ltime[i],lscore[i]])
  53. print (table)

总结:用nth-of-type的感觉太爽了,代码也要优美很多。

文章来源: blog.csdn.net,作者:悦来客栈的老板,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/qq523176585/article/details/82917075

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。