python爬取豆瓣电影TOP250数据

作者:秋无之地 时间:2021-12-27 12:50:17 

在执行程序前,先在MySQL中创建一个数据库"pachong"。


import pymysql
import requests
import re

#获取资源并下载
def resp(listURL):
   #连接数据库
   conn = pymysql.connect(
       host = '127.0.0.1',
       port = 3306,
       user = 'root',
       password = '******',  #数据库密码请根据自身实际密码输入
       database = 'pachong',
       charset = 'utf8'
   )

#创建数据库游标
   cursor = conn.cursor()

#创建列表t_movieTOP250(执行sql语句)
   cursor.execute('create table t_movieTOP250(id INT PRIMARY KEY auto_increment NOT NULL ,movieName VARCHAR(20) NOT NULL ,pictrue_address VARCHAR(100))')

try:
       # 爬取数据
       for urlPath in listURL:
           # 获取网页源代码
           response = requests.get(urlPath)
           html = response.text

# 正则表达式
           namePat = r'alt="(.*?)" src='
           imgPat = r'src="(.*?)" class='

# 匹配正则(排名【用数据库中id代替,自动生成及排序】、电影名、电影海报(图片地址))
           res2 = re.compile(namePat)
           res3 = re.compile(imgPat)
           textList2 = res2.findall(html)
           textList3 = res3.findall(html)

# 遍历列表中元素,并将数据存入数据库
           for i in range(len(textList3)):
               cursor.execute('insert into t_movieTOP250(movieName,pictrue_address) VALUES("%s","%s")' % (textList2[i],textList3[i]))

#从游标中获取结果
       cursor.fetchall()

#提交结果
       conn.commit()
       print("结果已提交")

except Exception as e:
       #数据回滚
       conn.rollback()
       print("数据已回滚")

#关闭数据库
   conn.close()

#top250所有网页网址
def page(url):
   urlList = []
   for i in range(10):
       num = str(25*i)
       pagePat = r'?start=' + num + '&filter='
       urL = url+pagePat
       urlList.append(urL)
   return urlList

if __name__ == '__main__':
   url = r"https://movie.douban.com/top250"
   listURL = page(url)
   resp(listURL)

结果如下图:

python爬取豆瓣电影TOP250数据

python爬取豆瓣电影TOP250数据

来源:https://www.cnblogs.com/qiuwuzhidi/p/14784302.html

标签:python,豆瓣,爬虫
0
投稿

猜你喜欢

  • Python Flask基础到登录功能的实现代码

    2022-01-04 14:29:57
  • Python 匹配任意字符(包括换行符)的正则表达式写法

    2023-01-23 23:11:09
  • Django中login_required装饰器的深入介绍

    2023-08-22 09:18:28
  • Python3 Tkinter选择路径功能的实现方法

    2022-03-12 19:39:28
  • Python获取网络时间戳的两种方法详解

    2023-04-11 06:38:21
  • php+mysqli实现批量替换数据库表前缀的方法

    2023-11-22 10:15:55
  • 常用的数据库备份类型有哪些?

    2009-11-01 13:02:00
  • PHP中的traits实现代码复用使用实例

    2023-11-22 04:27:55
  • javascript分页代码实例分享(js分页)

    2023-10-11 10:00:57
  • 怎么样在网页上读取远程xml的数据

    2008-10-10 17:43:00
  • Python使用UDP实现720p视频传输的操作

    2023-12-04 09:32:49
  • python 动态调用函数实例解析

    2021-03-11 09:31:41
  • php session处理的定制

    2023-11-15 18:38:12
  • Python操作Excel把数据分给sheet

    2023-08-07 17:03:53
  • Laravel实现队列的示例代码

    2023-05-28 04:39:21
  • ASP ,IP地址分段计算

    2008-04-13 06:55:00
  • python selenium自动化测试框架搭建的方法步骤

    2023-05-24 21:38:49
  • 趣用文化元素

    2009-09-03 11:53:00
  • php微信公众号开发之快递查询

    2023-11-11 03:30:36
  • 简单谈谈Python流程控制语句

    2023-03-12 12:34:25
  • asp之家 网络编程 m.aspxhome.com