基础页面:https://movie.douban.com/top250

  代码:

from time import sleep
from requests import get
from bs4 import BeautifulSoup
import re
import pymysql db = pymysql.connect(host='localhost',
user='root',
password='123456',
db='douban',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor
)
try:
with db.cursor() as cursor:
sql = "CREATE TABLE IF NOT EXISTS `top250` (" \
"`id` int(6) NOT NULL AUTO_INCREMENT," \
"`top` int(6) NOT NULL," \
"`page-code` int(6) NOT NULL," \
"`title` varchar(255) NOT NULL," \
"`origin-title` varchar(255)," \
"`score` float NOT NULL," \
"`theme` varchar(255) NOT NULL," \
"PRIMARY KEY(`id`)" \
") ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;"
cursor.execute(sql,)
finally:
db.commit() base_url = 'https://movie.douban.com/top250'
header = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Cookie': 'xxx',
'Host': 'movie.douban.com',
'Referer': 'https://movie.douban.com/chart',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'xxx'
} def crawler(url=None, headers=None, delay=1):
r = get(url=url, headers=headers, timeout=3)
soup = BeautifulSoup(r.text, 'html.parser')
page_tag = soup.find('span', attrs={'class': 'thispage'})
page_code = re.compile(r'<span class="thispage">(.*)</').findall(str(page_tag))[0]
movie_ranks = soup.find_all('em', attrs={'class': ''})
movie_titles = soup.find_all('div', attrs={'class': 'hd'})
movie_scores = soup.find_all('span', attrs={'class': 'rating_num'})
movie_themes = soup.find_all('span', attrs={'class': 'inq'})
next_page = soup.find('link', attrs={'rel': 'next'})
for ranks, titles, scores, themes in zip(movie_ranks, movie_titles, movie_scores, movie_themes):
rank = re.compile(r'<em class="">(.*)</').findall(str(ranks))
regex_ts = re.compile(r'<span class="title">(.*)</').findall(str(titles))
title = regex_ts[0]
score = re.compile(r'<span class="rating_num" property="v:average">(.*)</').findall(str(scores))[0]
theme = re.compile(r'<span class="inq">(.*)</').findall(str(themes))[0]
try:
origin_title = regex_ts[1]
origin_title = re.compile(r'./.(.+)').findall(origin_title)[0]
with db.cursor() as cursor:
sql = "INSERT INTO `top250` (`top`, `page-code`, `title`, `origin-title`, `score`, `theme`)" \
" VALUES (%s, %s, %s, %s, %s, %s)"
cursor.execute(sql, (rank, page_code, title, origin_title, score, theme,))
except IndexError:
with db.cursor() as cursor:
sql = "INSERT INTO `top250` (`top`, `page-code`, `title`, `score`, `theme`)" \
" VALUES (%s, %s, %s, %s, %s)"
cursor.execute(sql, (rank, page_code, title, score, theme,))
finally:
db.commit()
if next_page is not None:
headers['Referer'] = url
next_url = base_url + re.compile(r'<link href="(.*)" rel="next">').findall(str(next_page))[0]
sleep(delay)
crawler(url=next_url, headers=headers, delay=3) crawler(base_url, header, 0)
db.close()

  结果:

mysql> select top,title,score from top250 where id = 175;
+-----+--------+-------+
| top | title | score |
+-----+--------+-------+
| 176 | 罗生门 | 8.7 |
+-----+--------+-------+
1 row in set (0.00 sec) mysql> select top,title,page-code,score from top250 where id = 175;
ERROR 1054 (42S22): Unknown column 'page' in 'field list'
mysql> select top,page-code,title,score from top250 where id = 175;
ERROR 1054 (42S22): Unknown column 'page' in 'field list'
mysql> select page-code from top250 where id = 175;
ERROR 1054 (42S22): Unknown column 'page' in 'field list'
mysql> describe top250
-> ;
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int(6) | NO | PRI | NULL | auto_increment |
| top | int(6) | NO | | NULL | |
| page-code | int(6) | NO | | NULL | |
| title | varchar(255) | NO | | NULL | |
| origin-title | varchar(255) | YES | | NULL | |
| score | float | NO | | NULL | |
| theme | varchar(255) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
7 rows in set (0.32 sec) mysql> select page-code from top250 where id = 175;
ERROR 1054 (42S22): Unknown column 'page' in 'field list'
mysql> select origin-title from top250 where id = 175;
ERROR 1054 (42S22): Unknown column 'origin' in 'field list'
mysql> select origin_title from top250 where id = 175;
ERROR 1054 (42S22): Unknown column 'origin_title' in 'field list'
mysql> select * from top250 where id = 175;
+-----+-----+-----------+--------+--------------+-------+-------------------+
| id | top | page-code | title | origin-title | score | theme |
+-----+-----+-----------+--------+--------------+-------+-------------------+
| 175 | 176 | 8 | 罗生门 | 羅生門 | 8.7 | 人生的N种可能性。 |
+-----+-----+-----------+--------+--------------+-------+-------------------+
1 row in set (0.00 sec) mysql> select * from top250 where title = 未麻的部屋;
ERROR 1054 (42S22): Unknown column '未麻的部屋' in 'where clause'
mysql> select * from top250 where top=175;
Empty set (0.00 sec) mysql>

  两个小问题:

  1.没想到数据库字段不能用'-'...,于是page-code字段与origin-title字段不能独立进行查找。。。

  2.不知道为啥top175的电影《未麻的部屋》没爬到。。。

  建议使用scrapy。

  用scrapy的一些好处是配置爬虫很方便,还有其内部自带的html解析器、对不完整的url的组建等十分便利。

  最后,吐槽一下,之前的电脑配置太差,跑深度学习程序的过程耗尽内存,出现莫名的bug后,蓝屏死机就再也没法启动了。。。所以,暂时不能更新博客了。。。

python3+requests+BeautifulSoup+mysql爬取豆瓣电影top250的更多相关文章

  1. 爬虫系列(十) 用requests和xpath爬取豆瓣电影

    这篇文章我们将使用 requests 和 xpath 爬取豆瓣电影 Top250,下面先贴上最终的效果图: 1.网页分析 (1)分析 URL 规律 我们首先使用 Chrome 浏览器打开 豆瓣电影 T ...

  2. urllib+BeautifulSoup无登录模式爬取豆瓣电影Top250

    对于简单的爬虫任务,尤其对于初学者,urllib+BeautifulSoup足以满足大部分的任务. 1.urllib是Python3自带的库,不需要安装,但是BeautifulSoup却是需要安装的. ...

  3. python2.7爬取豆瓣电影top250并写入到TXT,Excel,MySQL数据库

    python2.7爬取豆瓣电影top250并分别写入到TXT,Excel,MySQL数据库 1.任务 爬取豆瓣电影top250 以txt文件保存 以Excel文档保存 将数据录入数据库 2.分析 电影 ...

  4. 一起学爬虫——通过爬取豆瓣电影top250学习requests库的使用

    学习一门技术最快的方式是做项目,在做项目的过程中对相关的技术查漏补缺. 本文通过爬取豆瓣top250电影学习python requests的使用. 1.准备工作 在pycharm中安装request库 ...

  5. 爬虫系列(十一) 用requests和xpath爬取豆瓣电影评论

    这篇文章,我们继续利用 requests 和 xpath 爬取豆瓣电影的短评,下面还是先贴上效果图: 1.网页分析 (1)翻页 我们还是使用 Chrome 浏览器打开豆瓣电影中某一部电影的评论进行分析 ...

  6. 【转】爬取豆瓣电影top250提取电影分类进行数据分析

    一.爬取网页,获取需要内容 我们今天要爬取的是豆瓣电影top250页面如下所示: 我们需要的是里面的电影分类,通过查看源代码观察可以分析出我们需要的东西.直接进入主题吧! 知道我们需要的内容在哪里了, ...

  7. Python爬虫入门:爬取豆瓣电影TOP250

    一个很简单的爬虫. 从这里学习的,解释的挺好的:https://xlzd.me/2015/12/16/python-crawler-03 分享写这个代码用到了的学习的链接: BeautifulSoup ...

  8. scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250

    scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250 前言 经过上一篇教程我们已经大致了解了Scrapy的基本情况,并写了一个简单的小demo.这次我会以爬取豆瓣电影TOP250为例进一步为大 ...

  9. scrapy爬取豆瓣电影top250

    # -*- coding: utf-8 -*- # scrapy爬取豆瓣电影top250 import scrapy from douban.items import DoubanItem class ...

随机推荐

  1. Jarvis OJ - class10 -Writeup

    Jarvis OJ - class10 -Writeup 转载请注明出处:http://www.cnblogs.com/WangAoBo/p/7552266.html 题目: Jarivs OJ的一道 ...

  2. css和js处理隔行换色的问题

      <html> <head> <meta charset="utf-8"> <meta name="" conten ...

  3. HTTP请求消息的数据格式

    servletRequest获取请求消息 Request 分为4部分1.请求行 格式:请求方式 请求url 请求协议/版本GET /login.html HTTP/1.1 特点:行和头之间没有任何分隔 ...

  4. AcWing 802. 区间和 离散化

    https://www.acwing.com/problem/content/804/ #include <iostream> #include <vector> #inclu ...

  5. 状态压缩DP入门题

    . /*本题为状态压缩题 题目大意 : 一个矩阵里有很多格子,每个格子有两种状态,可以放牧和不可以放牧, 可以放牧用1表示,否则用0表示,在这块牧场放牛,要求两个相邻的方 格不能同时放牛(不包括斜着的 ...

  6. DFT计算过程详解

    DFT计算过程详解 平时工作中,我们在计算傅里叶变换时,通常会直接调用Matlab中的FFT函数,或者是其他编程语言中已经为我们封装好的函数,很少去探究具体的计算过程,本文以一个具体的例子,向你一步一 ...

  7. HTML学习(2)编辑器

    HTML编辑常用的编辑器:Notepad++.Sublime Text.VS Code 可以使用Emmet插件来提高编码速度. 注:emmet只支持32位的Notepad++. 注意这里要把这两个dl ...

  8. MySQL对大小写敏感吗

    见字如面,见标题知内容.你有遇到过因为MYSQL对大小写敏感而被坑的体验吗? 之前看过阿里巴巴Java开发手册,在MySql建表规约里有看到: [强制]表名.字段名必须使用小写字母或数字 , 禁止出现 ...

  9. MinGW编译dll并引用

    记得某位神仙曾经说过:一个项目不使用dll简直是一场灾难.(滑稽) 这篇文章以A+B/A-B为范例,来介绍如何在MinGW下编译dll并引用. 首先你要安装MinGW,并配置好环境变量(不配置环境变量 ...

  10. liunx详解-2

    linux安装与配置 安装配置 虚拟机配置1G内存,1核CPU,50G硬盘,网络地址转换(NAT,主机作为路由构建内网) 镜像文件:http://mirror.nsc.liu.se/centos-st ...