php中文网 | cnphp.com

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
查看: 484|回复: 0

豆瓣爬虫到数据库

[复制链接]

2573

主题

2580

帖子

9105

积分

管理员

Rank: 9Rank: 9Rank: 9

UID
1
威望
0
积分
6410
贡献
0
注册时间
2021-4-14
最后登录
2024-3-29
在线时间
653 小时
QQ
发表于 2022-5-18 08:50:43 | 显示全部楼层 |阅读模式
[mw_shl_code=python,true]from selenium.webdriver import Chrome
import re
import pymysql
from pymysql.converters import escape_string
web=Chrome()
web.get("https://movie.douban.com/top250")
#获取数据库的链接
conn=pymysql.connect(
        db="douban516",
        user="root",
        passwd="103415",
        port=3306,
        charset="utf8"
    )
# 实现将数据保存到数据库的功能
def saveToMySQL(data):
    print("正在保存数据到数据库.....")

    #获取数据库的游标
    cur=conn.cursor()
    #执行sql语句
    sql="insert into movie(moviename, href, director, pf, judgenum, gs) values('%s','%s','%s','%s','%s','%s')"
    #执行sql
    # print(sql%data)
    cur.execute(sql%data)

while True:
    lis = web.find_elements_by_xpath('//*[@id="content"]/div/div[1]/ol/li')

    for li in lis:
        # 获取电影名称
        moviename = li.find_element_by_xpath('.//div[@class="hd"]/a').text
        moviename=escape_string(moviename)
        # 获取a的href链接
        href = li.find_element_by_xpath('.//div[@class="hd"]/a').get_attribute("href")
        # 获取导演信息
        director = li.find_element_by_xpath('.//div[@class="bd"]//p').text
        director=escape_string(director)
        # 获取评分信息
        pf = li.find_element_by_xpath('.//span[@class="rating_num"]').text
        # 获取评论人数
        judgenum = li.find_element_by_xpath('.//div[@class="star"]/span[4]').text
        # 使用正则表达式获取评价人数的数字
        judgenum = re.findall('\d+', judgenum)
        # 使用findall方法返回的是一个列表 需要转成字符串
        judgenum = ''.join(judgenum)
        # 获取影片的概述信息
        try:
            gs = li.find_element_by_xpath('.//span[@class="inq"]').text
            gs=escape_string(gs)
        except:
            gs=""
        mess_tup = (moviename, href, director, pf, judgenum, gs)
        #保存数据到数据库
        saveToMySQL(mess_tup)
        # print(mess_tup)
    try:
        web.find_element_by_xpath('//span[@class="next"]/a').click()
        web.implicitly_wait(5)
    except:
        break
web.close()[/mw_shl_code]





上一篇:雷达模糊函数
下一篇:c语言遍历二叉树
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|php中文网 | cnphp.com ( 赣ICP备2021002321号-2 )51LA统计

GMT+8, 2024-3-29 15:36 , Processed in 0.238072 second(s), 36 queries , Gzip On.

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2020, Tencent Cloud.

申明:本站所有资源皆搜集自网络,相关版权归版权持有人所有,如有侵权,请电邮(fiorkn@foxmail.com)告之,本站会尽快删除。

快速回复 返回顶部 返回列表