Python爬虫爬取豆瓣电影名称和链接,分别存入txt,excel和数据库
前提条件是python操作excel和数据库的环境配置是完整的,这个需要在python中安装导入相关依赖包;
实现的具体代码如下:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import urllib
import urllib2
import sys
import re
import ssl
import openpyxl
import MySQLdb
import time
#from bs4 import BeautifulSoup
#修改系统默认编码为utf-8
reload(sys)
sys.setdefaultencoding("utf-8")
ssl._create_default_https_context = ssl._create_unverified_context
#创建全局列表存储数据,存放电影名字和链接地址
nameLists = []
linkLists = []
#搜索豆瓣top100电影,保存成文件、excel、数据库
class TopMove:
#初始化
def __init__(self):
#self.page = page
#self.nameList = []
#self.linkList = []
self.URL = 'https://movie.douban.com/top250?start='
def GetHTML(self,page):
#for page in rang(10):
try:
url = self.URL + str(page * 25)
request = urllib2.Request(url)
response = urllib2.urlopen(request)
html = response.read().decode('utf-8')
#print html
return html
#链接报错的原因
except urllib2.URLError, e:
if hasattr(e,"reason"):
print u'链接豆瓣电影失败,错误原因:',e.reason
return None
def GetList(self):
#nameLists = []
#linkLists = []
for page in range(10):
print "正在获取电影列表" + str(page+1)
#print str(page)
html = self.GetHTML(page)
#因为title的电影名有些存在两个title标签,所以就在img中去正则匹配
name = re.compile('<img alt="(.*?)".*?>',re.S)
link = re.compile('<div class="hd">.*?<a.*?href="(.*?)".*?>.*?</a>',re.S)
nameList = re.findall(name,html)
linkList = re.findall(link,html)
for name in nameList:
#剔除英文名包含“/”
if name.find('/') == -1:
nameLists.append(name)
for link in linkList:
linkLists.append(link)
#nameLists.append(nameList[0].strip())
#linkLists.append(linkList[0].strip())
#print nameList
#print linkList
print "获取完毕"
return nameLists,linkLists
#保存为文本文件
def save_Text(self):
#List = []
#List = self.GetList(page)
try:
f = open('D:\learn\date.txt','a')
for i in range(250):
#循环写入名称和地址
f.write(nameLists[i])
f.write('\t'*3)
f.write(linkLists[i])
f.write('\n')
#关闭文件
f.close()
except Exception as e:
print e
print u"文件存储结束"
#保存为excel格式
def save_Excel(self):
#List = []
#List = self.GetList()
try:
#新建workbook
wb = openpyxl.Workbook()
#去工作表的sheet页
sheet = wb.get_active_sheet()
#sheet页命名
sheet.title = 'Move Top 250'
for i in range(1,251):
one = 'a' + str(i) #a1,a列
two = 'b' + str(i) #b2,b列
sheet[one] = nameLists[i-1]
sheet[two] = linkLists[i-1]
#print nameLists[i-1]
#print linkLists[i-1]
#保存文件格式,文件名为中文
wb.save(ur'D:/learn/豆瓣电影TOP250.xlsx')
except Exception as e:
print e
print 'Excel 文件存储结束'
#保存到数据库中本地
def save_Mysql(self):
#List = []
#List = self.GetList()
try:
#链接数据库
conn = MySQLdb.connect(
host='localhost',
port=3306,
user='root',
passwd='lebb123',
db='pytest',
charset='utf8'
)
#获取操作游标
cursor = conn.cursor()
print 'Connecting to MYSQL Success'
#如果表存在就删除
cursor.execute('Drop table if EXISTS MovieTop')
time.sleep(3)
#创建一个数据库表
cursor.execute(
"""create table if not EXISTS MovieTop(
id int(4) not null primary key auto_increment,
movieName varchar(200),
link varchar(200));"""
)
for i in range(250):
#插入数据库数据sql
sql = 'insert into MovieTop(movieName,link) VALUES (%s,%s)'
param = (nameLists[i],linkLists[i])
#print nameLists[i],linkLists[i]
#执行SQL
cursor.execute(sql,param)
#提交到数据库执行
conn.commit()
cursor.close()
conn.close()
except Exception as e:
print e
print "Data Success Save in MYSQL"
def Start(self):
self.GetList()
self.save_Text()
self.save_Excel()
#wb = self.save_Excel()
self.save_Mysql()
dytop = TopMove()
dytop.Start()
Python爬虫爬取豆瓣电影名称和链接,分别存入txt,excel和数据库的更多相关文章
- Python爬虫爬取豆瓣电影之数据提取值xpath和lxml模块
工具:Python 3.6.5.PyCharm开发工具.Windows 10 操作系统.谷歌浏览器 目的:爬取豆瓣电影排行榜中电影的title.链接地址.图片.评价人数.评分等 网址:https:// ...
- python 爬虫&爬取豆瓣电影top250
爬取豆瓣电影top250from urllib.request import * #导入所有的request,urllib相当于一个文件夹,用到它里面的方法requestfrom lxml impor ...
- python爬虫-爬取豆瓣电影数据
#!/usr/bin/python# coding=utf-8# 作者 :Y0010026# 创建时间 :2018/12/16 16:27# 文件 :spider_05.py# IDE :PyChar ...
- Python爬虫-爬取豆瓣电影Top250
#!usr/bin/env python3 # -*- coding:utf-8-*- import requests from bs4 import BeautifulSoup import re ...
- python爬虫 Scrapy2-- 爬取豆瓣电影TOP250
sklearn实战-乳腺癌细胞数据挖掘(博主亲自录制视频) https://study.163.com/course/introduction.htm?courseId=1005269003& ...
- 写一个python 爬虫爬取百度电影并存入mysql中
目标是利用python爬取百度搜索的电影 在类型 地区 年代各个标签下 电影的名字 评分 和图片连接 以及 电影连接 首先我们先在mysql中建表 create table liubo4( id in ...
- Python爬虫----抓取豆瓣电影Top250
有了上次利用python爬虫抓取糗事百科的经验,这次自己动手写了个爬虫抓取豆瓣电影Top250的简要信息. 1.观察url 首先观察一下网址的结构 http://movie.douban.com/to ...
- Python爬虫爬取豆瓣读书
一,准备工作. 工具:win10+Python3.6 爬取目标:爬取图中红色方框的内容. 原则:能在源码中看到的信息都能爬取出来. 信息表现方式:CSV转Excel. 二,具体步骤. 先给出具体代码吧 ...
- python3 爬虫---爬取豆瓣电影TOP250
第一次爬取的网站就是豆瓣电影 Top 250,网址是:https://movie.douban.com/top250?start=0&filter= 分析网址'?'符号后的参数,第一个参数's ...
随机推荐
- TodoMVC中的Backbone+MarionetteJS+RequireJS例子源码分析之三 Views
这个版本的TodoMVC中的视图组织划分比较细,更加易于理解,这也得益于Marionette为我们带来了丰富的视图选择,原生的backbone只有views,而Marionette则有itemview ...
- java-集合3
浏览以下内容前,请点击并阅读 声明 Queue接口(队列) 需要对一些列的元素进行处理前,我们可以把他们放到Queue对象中,除了继承Collection接口的方法外,队列还有一些插入,删除和检查操作 ...
- Leetcode Divide Two Integers
Divide two integers without using multiplication, division and mod operator. 不用乘.除.求余操作,返回两整数相除的结果,结 ...
- PKUSC2016
day x(x<0) 外出培训倒数第二天晚上发烧了....逃过了第二天早上的考试,orz 抢到rank 1 的commonc神犇!! day 0 下午到了北大,发了两张50元饭卡.这是第三次来北 ...
- POJ 1637 Sightseeing tour(混合图的欧拉回路)
题目链接 建个图,套个模板. #include <cstdio> #include <cstring> #include <iostream> #include & ...
- pythonchallenge 解谜
所有代码均使用python 3.5.1 版本 最近在学python,闲来无事觉得这个解谜还挺有意思. 解谜网址 http://www.pythonchallenge.com/ 接下来会写破解教程~
- c#向数据库插入较大数据(SqlBulkCopy)
因为要向数据库添加一些数据,数据量较大 1.使用sql语句批量提交速度较慢 2.用事物批量提交,速度一般 3.用SqlBulkCopy方法写入数据,速度较快 /// <summary> / ...
- 2016huasacm暑假集训训练四 递推_A
题目链接:http://acm.hust.edu.cn/vjudge/contest/125308#problem/A 这题主要考的就是就是一个排列公式,但是不能用阶乘的公式, 用这个公式不易超 ...
- 将List下载到本地保存为Excel
直接附上代码 /// <summary> /// 将List保存为Excel /// </summary> /// <typeparam name="T&quo ...
- Random随机类(11选5彩票)BigInteger大数据类(华为面试题1000的阶乘)
先上Java Web图 为了简化叙述,只写Java代码,然后控制台输出 使用[Random类]取得随机数 import java.util.Random; public class Fir { pub ...