Dotcpp  >  编程教程  >  Python实战项目  >  Python爬虫入门抓取豆瓣内容三(附完整代码)

Python爬虫入门抓取豆瓣内容三(附完整代码)

点击打开在线编译器,边学边练

上一节我们通过数据分析,找到了我们想要的内容,我们这一节就把这些内容保存到数据库中,来方便我们随时查看。

本节我们采用PyMySQL数据库以及txt文件两种方式来保存数据。

1. 完整代码

import re
import requests
import pymysql
from bs4 import BeautifulSoup
qy = open('C:/Users/轻烟/Desktop/db.txt',mode='a',encoding='utf-8')#这里是要存入的文件目录
for i in range(1):
    headers = {#这里模拟浏览器进行访问
        'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) 
        AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.82 Safari/537.36',
        'Host': 'movie.douban.com'
    }
    res = 'https://movie.douban.com/top250?start='+str(25*i)#25次
    r = requests.get(res, headers=headers, timeout=10)#设置超时时间
    soup = BeautifulSoup(r.text, "html.parser")#设置解析方式,也可以使用其他方式。
    div_list = soup.find_all('div', class_='item')
    movies = []
    for each in div_list:
        movie = {}
        moviename = each.find('div', class_='hd').a.span.text.strip()
        movie['title'] = moviename
        rank = each.find('div', class_='pic').em.text.strip()
        movie['rank'] = rank
        info = each.find('div', class_='bd').p.text.strip()
        info = info.replace('\n', "")
        info = info.replace(" ", "")
        info = info.replace("\xa0", "")
        director = re.findall(r'[导演:].+[主演:]', info)[0]
        director = director[3:len(director) - 6]
        movie['director'] = director
        release_date = re.findall(r'[0-9]{4}', info)[0]
        movie['release_date'] = release_date
        plot = re.findall(r'[0-9]*[/].+[/].+', info)[0]
        plot = plot[1:]
        plot = plot[plot.index('/') + 1:]
        plot = plot[plot.index('/') + 1:]
        movie['plot'] = plot
        star = each.find('div', class_='star')
        star = star.find('span', class_='rating_num').text.strip()
        movie['star'] = star
        movies.append(movie)
        print(movie,file=qy)#保存到文件中
con = pymysql.connect(host = 'localhost', user = 'root',password = '123456',database ='python',
charset = 'utf8',port = 3306)
print('连接成功->')
cursor =  con.cursor()#创建一个游标
print('开始创建表->')
cursor.execute("""create table douban
                ( title char(40),
                  ranks char(40),
                  director char(40),
                  release_date char(40), 
                  plot char(100),
                  star char(40))
               """)
print('完成表的创建,开始插入数据->')#下面开始插入数据
for i in movies:
    cursor.execute("insert into douban(title,ranks,director,release_date,plot,star) "
                   "values(%s,%s,%s,%s,%s,%s)",(i['title'],i['rank'],i['director'],
                   i['release_date'],i['plot'],i['star']))
print('插入数据完成')
cursor.close()
con.commit()
con.close()

2. 代码分析

爬虫部分的代码我们在上一节已经分析过了,这一节我们主要来分析数据库部分。

首先是连接数据库,相关信息要和自己的数据库相对应,详细连接方式可以参考前面的数据库章节。

con = pymysql.connect(host = 'localhost', user = 'root',password = '123456',database ='python',
charset = 'utf8',port = 3306)
print('连接成功->')
cursor =  con.cursor()#创建一个游标

然后创建一个表来保存这些数据

print('开始创建表->')
cursor.execute("""create table douban
                ( title char(40),
                  ranks char(40),
                  director char(40),
                  release_date char(40), 
                  plot char(100),
                  star char(40))
               """)

由于我们已经把数据保存在了名为movies的列表中,我们遍历这个列表来插入数据即可插入的时候需要注意,前面数据库章节中插入数据是直接在values中用引号来完成,这里因为我们插入的是变量,不是string类型,因此我们要用占位符来插入数据,插入的格式如下。

for i in movies:
    cursor.execute("insert into douban(title,ranks,director,release_date,plot,star) "
                   "values(%s,%s,%s,%s,%s,%s)",(i['title'],i['rank'],i['director'],
                   i['release_date'],i['plot'],i['star']))

这样就完成了数据的保存,我们可以在数据库中直接来浏览这些信息,这样就完成了数据的保存。

3. 运行结果

数据库文件:

 爬取豆瓣电影信息5

txt文件中:

爬取豆瓣电影信息6

4. 总结

在这个例子中,我们结合了爬虫、BeautifulSoup和数据库三个部分,数据检查使用的比较少了解一下即可,爬虫项目大致就是这样一个流程,当然这个只是一个比较基础的爬虫练习,如果有兴趣的同学可以参考下面的网站去找一个项目动手练习:https://www.jb51.net/article/164829.htm



本文固定URL:https://www.dotcpp.com/course/330

Python教程
第一章 Python入门
第二章 Python基础语法
第三章 Python入门语法
第四章 Python核心语法
第五章 Python函数
第六章 Python面向对象编程
第七章 Python模块
第八章 Python异常处理和程序调试
第九章 Python文件及目录操作
第十章 PythonGUI编程
第十一章 Python进程和线程
第十二章 Python数据库管理
第十三章 Python算法
第十四章 Python爬虫
第十五章 Python实战项目
第十六章 后记
Dotcpp在线编译      (登录可减少运行等待时间)