[python爬虫]爬取电影天堂连接

导包

import requests,re,chardet,pymysql
from piaot import *

获取首页一共有多少个分类

def shoye():
    url='http://www.dytt8.net/html/gndy/dyzz/index.html'
    headers={
        "User-Agent":pa()
    }
    req=requests.get(url,headers=headers)
    req.encoding= 'gb2312'
    html=req.text

    # 正则
    zz='<a href="(.*?)">(.*?)</a></li><li>'
    str_1 = re.compile(zz)
    html = str_1.findall(html)

    # 取出我们想要的数据
    html=html[:11]

    lie_list=[]
    for i in html:
        if 'http://www.ygdy8.net' in  i[0]:
            lie_list.append((i[0],i[1]))
        else:
            a='http://www.ygdy8.net'+i[0]
            lie_list.append((a,i[1]))


    return lie_list

子类爬取

def zl(url):
    html=''
    try:
        req=yc(url)
        c=chardet.detect(req)
        html=req.decode(c['encoding'])
    except:
        zl(url)
    # 正则
    zz='<a href="(.*?)" class="ulink">(.*?)</a>'
    lian_jie=re.compile(zz)
    html=lian_jie.findall(html)
    if html == []:
        zl(url)
    else:
        for i in html:
            z_url='http://www.ygdy8.net'+i[0]
            sql_url=pq_tp(z_url)
            print('存储中.....')

            dy_name=str(i[1])
            sql_url=str(sql_url)

            # msql存储
            sql_z = "insert into dy(uname,lianjie) values({},'{}');".format(dy_name,sql_url)
            # print(sql_z)
            sql(sql_z)
            return html

爬取视频连接

def pq_tp(url):

    try:
        print('爬取数据中..........')
        req=yc(url)
        x=chardet.detect(req)
        html=req.decode(x['encoding'])

        # 正则
        zz='<td style="WORD-WRAP: break-word" bgcolor=".*"><a href="(.*?)">'
        dy_url=re.compile(zz)
        html=dy_url.findall(html)

        if html == []:

            pq_tp(url)
        else:
            print('爬取成功!',html[0])
            return html[0]
    except:

        pq_tp(url)

调用mysql

def sql(sql_z):
    # 打开数据库连接
    db = pymysql.connect("192.168.43.128", "root", "123456", "dianying", charset='utf8')

    # 使用 cursor() 方法创建一个游标对象 cursor
    cursor = db.cursor()

    # 使用 execute()  方法执行 SQL 查询
    cursor.execute("")

    # 使用 fetchone() 方法获取单条数据.
    data = cursor.fetchone(sql_z)

    print("Database version : %s " % data)

    # 关闭数据库连接
    db.close()

if name == ‘main‘:

调用函数

shoye()

猜你喜欢

转载自blog.csdn.net/Black_God1/article/details/81873517