python3抓取豆瓣TOP250结果存mysql

一、项目简介

1.内容:使用python抓取豆瓣TOP电影的名字、详情页链接存mysql,网页由xpath来解析

2.豆瓣网:https://movie.douban.com/top250

3.软件:pycharm、mysql

4.python3

5.涉及类库:lxml、requests、pymysql

二、思路

1.安装导入类库

import pymysql
import requests
from lxml import etree

2.分析网页获取TOP250所有网址

# top250所有网页网址
def get_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

3.分析网页xpath解析

namePat = html.xpath('//div[@class="hd"]/a/span[1]/text()')
infoPat = html.xpath('//div[@class="hd"]/a/@href')

4.数据库连接操作+请求头+xpath解析

注意:要先新建一个数据库名为 ‘only’

# 获取资源并下载
def get_sql(listURL):
    # 连接数据库
    conn = pymysql.connect(
        host='127.0.0.1',   # 本地
        port=3306,          # 端口
        user='root',        # 用户名
        password='******',  # 密码  自定义
        database='only',    # 数据库名
        charset='utf8'      # 编码 注意是utf8
    )

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

    # 创建表 movieTOP250(执行sql语句)
    # auto_increment 自增列    必须具备 not null
    sql_1 = 'create table TOP250(id int primary key auto_increment not null ,movieName varchar(20) not null,info varchar(120))'
    cursor.execute(sql_1)

    try:
        # 爬取数据
        header = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
        for urlPath in listURL:
            # 获取网页源代码
            response = requests.get(urlPath, headers=header)
            html_l = response.text

            html = etree.HTML(html_l)  # 初始化 xpath解析

            namePat = html.xpath('//div[@class="hd"]/a/span[1]/text()')
            infoPat = html.xpath('//div[@class="hd"]/a/@href')

            # 遍历列表中元素,并将数据存入数据库
            for i in range(len(infoPat)):
                print(namePat[i])
                # 执行数据库操作
                sql_2 = 'insert into TOP250(movieName,info) VALUES ("%s","%s")'
                cursor.execute(
                    sql_2 % (namePat[i], infoPat[i])
                )

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

        '''
        cursor.fetchone():将只取最上面的第一条结果
        cursor.fetchall():将返回所有结果
        python在mysql在使用fetchall或者是fetchone时,综合起来讲,fetchall返回二维元组(元组中含有元组),fetchone只返回一维元组。
        '''

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

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

三、最终代码

# python
# -*- coding:utf-8 -*-
# author:Only time:2019/8/14

# 豆瓣电影TOP250  爬取数据(排名、电影名、详情页)存mysql

import pymysql
import requests
from lxml import etree


# 获取资源并下载
def get_sql(listURL):
    # 连接数据库
    conn = pymysql.connect(
        host='127.0.0.1',   # 本地
        port=3306,          # 端口
        user='root',        # 用户名
        password='123qwe',  # 密码
        database='only',    # 数据库名
        charset='utf8'      # 编码 注意是utf8
    )

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

    # 创建表 movieTOP250(执行sql语句)
    # auto_increment 自增列    必须具备 not null
    sql_1 = 'create table TOP250(id int primary key auto_increment not null ,movieName varchar(20) not null,info varchar(120))'
    cursor.execute(sql_1)

    try:
        # 爬取数据
        header = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
        for urlPath in listURL:
            # 获取网页源代码
            response = requests.get(urlPath, headers=header)
            html_l = response.text

            html = etree.HTML(html_l)  # 初始化 xpath解析

            namePat = html.xpath('//div[@class="hd"]/a/span[1]/text()')
            infoPat = html.xpath('//div[@class="hd"]/a/@href')

            # 遍历列表中元素,并将数据存入数据库
            for i in range(len(infoPat)):
                print(namePat[i])
                # 执行数据库操作
                sql_2 = 'insert into TOP250(movieName,info) VALUES ("%s","%s")'
                cursor.execute(
                    sql_2 % (namePat[i], infoPat[i])
                )

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

        '''
        cursor.fetchone():将只取最上面的第一条结果
        cursor.fetchall():将返回所有结果
        python在mysql在使用fetchall或者是fetchone时,综合起来讲,fetchall返回二维元组(元组中含有元组),fetchone只返回一维元组。
        '''

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

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


# top250所有网页网址
def get_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 = get_page(url)
    get_sql(listURL)

四、运行结果

五、查看数据

发布了22 篇原创文章 · 获赞 18 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43930694/article/details/99636806