python3+requests+BeautifulSoup+mysql爬取豆瓣电影top250
基础页面: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的更多相关文章
- 爬虫系列(十) 用requests和xpath爬取豆瓣电影
这篇文章我们将使用 requests 和 xpath 爬取豆瓣电影 Top250,下面先贴上最终的效果图: 1.网页分析 (1)分析 URL 规律 我们首先使用 Chrome 浏览器打开 豆瓣电影 T ...
- urllib+BeautifulSoup无登录模式爬取豆瓣电影Top250
对于简单的爬虫任务,尤其对于初学者,urllib+BeautifulSoup足以满足大部分的任务. 1.urllib是Python3自带的库,不需要安装,但是BeautifulSoup却是需要安装的. ...
- python2.7爬取豆瓣电影top250并写入到TXT,Excel,MySQL数据库
python2.7爬取豆瓣电影top250并分别写入到TXT,Excel,MySQL数据库 1.任务 爬取豆瓣电影top250 以txt文件保存 以Excel文档保存 将数据录入数据库 2.分析 电影 ...
- 一起学爬虫——通过爬取豆瓣电影top250学习requests库的使用
学习一门技术最快的方式是做项目,在做项目的过程中对相关的技术查漏补缺. 本文通过爬取豆瓣top250电影学习python requests的使用. 1.准备工作 在pycharm中安装request库 ...
- 爬虫系列(十一) 用requests和xpath爬取豆瓣电影评论
这篇文章,我们继续利用 requests 和 xpath 爬取豆瓣电影的短评,下面还是先贴上效果图: 1.网页分析 (1)翻页 我们还是使用 Chrome 浏览器打开豆瓣电影中某一部电影的评论进行分析 ...
- 【转】爬取豆瓣电影top250提取电影分类进行数据分析
一.爬取网页,获取需要内容 我们今天要爬取的是豆瓣电影top250页面如下所示: 我们需要的是里面的电影分类,通过查看源代码观察可以分析出我们需要的东西.直接进入主题吧! 知道我们需要的内容在哪里了, ...
- Python爬虫入门:爬取豆瓣电影TOP250
一个很简单的爬虫. 从这里学习的,解释的挺好的:https://xlzd.me/2015/12/16/python-crawler-03 分享写这个代码用到了的学习的链接: BeautifulSoup ...
- scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250
scrapy爬虫框架教程(二)-- 爬取豆瓣电影TOP250 前言 经过上一篇教程我们已经大致了解了Scrapy的基本情况,并写了一个简单的小demo.这次我会以爬取豆瓣电影TOP250为例进一步为大 ...
- scrapy爬取豆瓣电影top250
# -*- coding: utf-8 -*- # scrapy爬取豆瓣电影top250 import scrapy from douban.items import DoubanItem class ...
随机推荐
- LitElement(三)Styles样式
1.为组件添加样式 import { LitElement, css, html } from 'lit-element'; class MyElement extends LitElement { ...
- hdu1716 排列2
12 21 123 132 213 231 321 312 .... 每次都将后面n-1位进行全排列.递归的出口当起始坐标等于终止坐标时.需要还原. 设计标记数组.因为需要从小到大输出. #def ...
- 【转】C# Application.DoEvent()的作用
Application.DoEvents()的作用:处理所有的当前在消息队列中的Windows消息. private void button1_Click(object sender, EventAr ...
- Java上传图片到Ftp,包含上传后文件大小为0的问题和Properties配置文件的读取
准备工作:需要使用coomos-net jar包.下载地址 一. 上传图片到FTP,文件大小为0的问题,解决:将ftp模式修改为Passive模式就可以了. //将ftp模式修改为Passive模式 ...
- Virtual Judge POJ 1328 Radar Installation
贪心 #include<algorithm> #include<iostream> #include<cstdio> #include<cmath> u ...
- DOJ1187 : 重建家园 (分数规划 && 二分 && kruskal)
最优答案一定是一颗树 那么二分比值,不断kruskal找到最大可以满足的解就可以了 代码如下 #include <cstdio> #include <algorithm> us ...
- HDU 6740 kmp最小循环节
题意:给一个无线循环小数的前几位,给n,m 选择其中一种出现在前几位的循环节方式(a个数),循环节的长度b 使得n*a-m*b最大 样例: 2 1 12.1212 输出 6 选择2,2*1-1*1=1 ...
- Django_连接MySQL
1. 在Settings中修改 2. 创建数据库 3. 连接mysql 4. pymysql 4.1 安装pymysql 在项目的init文件中添加 Django2.2 不需要伪装
- 【C语言】用C语言输出一个吃豆人
大圆盘减去扇形和小圆盘: #include <math.h> #include <stdio.h> int main() { double x, y; ; y >= -; ...
- winform学习(8)RichTextBox控件
RichTextBox控件允许用户输入和编辑文本的同时提供了比普通的TextBox控件更高级的格式特征. RichTextBox的控件标识符.SelectionColor = Color.Blue; ...