python3.7爬取豆瓣前250个电影名字并且写入mysql数据库

# !/usr/bin/python

# coding:utf-8


import requests


from bs4 import BeautifulSoup

import pymysql

print('连接到mysql服务器...')
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="root", database="test_1", charset="utf8")
print('连接上了!')
cursor = conn.cursor()
cursor.execute("DROP TABLE IF EXISTS MOVIE")
sql = """CREATE TABLE MOVIE (
        NAME CHAR(100) NOT NULL
         )"""

cursor.execute(sql)


test_url = 'http://movie.douban.com/top250/'


def download_page(url):
    headers = {

        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'

    }

    data = requests.get(url, headers=headers).content

    return data


movie_name_list = []


def parse_html(lxml):
    soup = BeautifulSoup(lxml)

    movie_list_soup = soup.find('ol', attrs={'class': 'grid_view'})

    if  movie_list_soup != None:

        for movie_li in movie_list_soup.find_all('li'):
            detail = movie_li.find('div', attrs={'class': 'hd'})

            movie_name = detail.find('span', attrs={'class': 'title'}).getText()

            movie_name_list.append(movie_name)

        next_page = soup.find('span', attrs={'class': 'next'}).find('a')

        if next_page:
            parse_html(download_page(test_url + next_page['href']))

        return movie_name_list



handle = parse_html(download_page(test_url))

if handle != None:

    handle = list(handle)

    for ele in handle:
        insert_color = ("INSERT INTO MOVIE(NAME)" "VALUES(%s)")
        date = ele
        cursor.execute(insert_color, date)
        conn.commit()
print ("插入成功")



 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值