基础页面: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. CentOS7.5升级OpenSSH

    实验环境 OS:CentOS 7.5 当前openssh版本:OpenSSH_7.4p1 升级后的openssh版本:OpenSSH_8.0p1 开通telnet 为了防止升级过程中ssh断连,保险起 ...

  2. 【蓝桥杯/算法训练】Sticks 剪枝算法

    剪枝算法 大概理解是通过分析问题,发现一些判断条件,避免不必要的搜索.通常应用在DFS 和 BFS 搜索算法中:剪枝策略就是寻找过滤条件,提前减少不必要的搜索路径. 问题描述 George took ...

  3. 随缘记录 LeetCode第168场周赛 2019-12-22

    5292. 划分数组为连续数字的集合 给你一个整数数组 nums 和一个正整数 k,请你判断是否可以把这个数组划分成一些由 k 个连续数字组成的集合. 如果可以,请返回 True:否则,返回 Fals ...

  4. VS2015+EF+MySql问题

    1.出现框架不兼容问题: 解决方法:a.在web.config或者app.config中加入所示代码: b.引用mysqlConnector.net中的所有dll,一般路径在D:\Program Fi ...

  5. ASP.NET + MVC5 入门完整教程七 -—-- MVC基本工具(下)

    https://blog.csdn.net/qq_21419015/article/details/80493633 Visual Stdio 的单元测试

  6. java多线程之wait和notify协作,生产者和消费者

    这篇直接贴代码了 package cn.javaBase.study_thread1; class Source { public static int num = 0; //假设这是馒头的数量 } ...

  7. 1.Java多线程之wait和notify

    1.首先我们来从概念上理解一下这两个方法: (1)obj.wait(),当obj对象调用wait方法时,这个方法会让当前执行了这条语句的线程处于等待状态(或者说阻塞状态),并释放调用wait方法的对象 ...

  8. codeforce F - Three Paths on a Tree

    F. Three Paths on a Tree time limit per test 2 seconds memory limit per test 256 megabytes input sta ...

  9. flutter_html 和 WebView 解析html 和 build.gradle源码

    一.flutter_html 涉及的 api 接口: http://www.phonegap100.com/appapi.php?a=getPortalArticle&aid=20 二.Flu ...

  10. 项目中的process.bpmn的读-过程

    1.这次项目中遇到了process.bpmn类的封装好的类.怎么读呢?不知道,一周过去了,总算明白点. 2.首先也是从Controller开始,走进service层,比如mybatis,调用的就不是m ...