py 爬取某网站直播集锦-上源码

test.py 核心代码

from contextlib import closing
from datetime import datetime
# 获取N 天前用到
from datetime import timedelta 
from time import sleep
# from xml.etree import ElementTree
import requests
import time
from store import ds
# from util import str_to_timestamp
import ssl
# from bs4 import BeautifulSoup
import json


# 使用普通方式进行请求 请求方式1
# 把请求封装成函数
def get(url):
    print('url: ', url)
    requests.packages.urllib3.disable_warnings()
    headers = {
        'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 '
                      'Safari/537.36 ',
        # json 无所谓
        # 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8;',
        # 'Accept-Language': 'zh-CN,zh;q=0.9',

        # 'Referer': 'https://www.dongqiudi.com/data/203'
    }

    resp = requests.get(url,timeout=10)
    return resp.text if resp.status_code == requests.codes.ok else None


# 直播吧 根据传入条件爬取 首页 完赛中 指定 比赛录像 集锦
# author bobo
# date 2020-03-27
def run():
    # 第一: 从 redis 或者 数据库中 读出 条件。
    date = '2020-03-27'
    home_team = 'VG'
    visit_team = 'LGD'

    # 第二: 请求 首页
    # 设置ssl
    # ssl._create_default_https_context = ssl._create_unverified_context
    # 这里没有强验证,所以就先不写了

    print('开始请求')    
    resp = get( 'https://bifen.qiumibao.com/json/' + date + '/list.htm')

    # 下面 封装成函数 最后了
    matches = matchName(resp,home_team,visit_team)

    print('第一次得到的matches: ', matches)

    if len(matches):
        # 存入数据库
        print('存入数据库: ', 存入数据库)
    else:
        # 提示当前找不到
        # 查询 15天之前的
        print('查询 15天之前的: ')
        allData = selectAll(home_team,visit_team)
        print('allData: ', allData)

        # 如果这里也没有 那就都木有了
        if len(allData):
            # 问问对方是否需要 再考虑是否存入数据库
            print('问问对方是否需要 再考虑是否存入数据库: ')
            print('allData: ', allData)
        else:
            # 啥都没有
            print('啥都没有: ')




    # if resp is None:
    #         return  

    # # 得到了json
    # source = json.loads(resp)#字符串转json
    # source = source['list']

    # length = len(source)
    # created_at = time.strftime("%Y-%m-%d %X",time.localtime())
    # print('开始更新')

    # # 这里得到的是每一条的 list  [{},{},{},{},{}]
    # for x in range(0,length):
    #     # 在这里匹配每一条 中是否 有 我们的数据
    #     if source[x]['home_team'] == home_team and source[x]['visit_team'] == visit_team:
    #         # 匹配到了 就打印出来
    #         print(source[x])
    #     else:
    #         print('抱歉查询不到')

    # # 这里到时候再加一个判断,如果还是查询不到,就直接 读取所有天数
    # allData = selectAll(home_team,visit_team)


# 15天中找到合适的数据
# 返回 []
def selectAll(home_team,visit_team):
    # 这里只能从15天中找到合适的数据了,看看用户是否需要.
    print('开始查询15天的')
    matches = []
    for i in range(0,16):
        # 当前的日期 开始 依次减少 i 天
        # get_date(i)
        print('get_date(i): ', get_date(i))
        resp = get( 'https://bifen.qiumibao.com/json/' + get_date(i) + '/list.htm')
        matches = matchName(resp,home_team,visit_team)
        # 这里收到的matches 保存起来
        # 带上日期存

    return matches


# 获取今天前第N天的日期
def get_date(days=0):
    res  = datetime.now() - timedelta(days=days)
    #转换为其他字符串格式: 
    dateTime = res.strftime("%Y-%m-%d")
    return dateTime

# 外界传入json 此处进行匹配
# 返回查询到的json 数据 [] 格式
def matchName(resp,home_team,visit_team):
    if resp is None:
            return  

    # 得到了json
    source = json.loads(resp)#字符串转json
    source = source['list']

    length = len(source)

    matches = []
    # 这里得到的是每一条的 list  [{},{},{},{},{}]
    for x in range(0,length):
        # 在这里匹配每一条 中是否 有 我们的数据
        if source[x]['home_team'] == home_team and source[x]['visit_team'] == visit_team:
            # 匹配到了 就打印出来
            url = source[x]['url']

            matches.append(combineUrl(url,1))
            matches.append(combineUrl(url,2))
        # else:
        #     print('抱歉查询不到')

    return matches

# 处理url 函数
# 把 api 返回的url 组装为 可get 的url 录像 集锦
# type 1 集锦 2 录像
def combineUrl(url,type):
    prefix = 'https://www.zhibo8.cc'
    combineIndex = url.find('.')
    url_prefix = prefix + url[0:int(combineIndex)]

    if type == 1:
        url_suffix = '-jijin.htm'
    else:
        url_suffix = '-luxiang.htm'

    return url_prefix + url_suffix

入口文件

import basketball.test

for module in [

    basketball.test,

]:

    print('Running', module.__name__, '...')

    try:

        module.run()

    except Exception as e:

        print(e)
本作品采用《CC 协议》,转载必须注明作者和本文链接
嗨,我是波波。曾经创业,有收获也有损失。我积累了丰富教学与编程经验,期待和你互动和进步! 公众号:上海PHP自学中心 付费知识星球:破解面试:程序员的求职导师
讨论数量: 5
Jason990420

有一些地方有点问题, 稍微改了一下 :)

  1. 用了我自己的 Read_URL
  2. 前十五天, range(1, 16)
  3. selectAll 没有存下每一笔的数据, 只返回最后一笔, 还有可能是 []
  4. 最后获取的url, 好像都是没用的URL, "404 Not Found"
from Tool import Read_URL
# Tool link:
# https://github.com/jason990420/jason990420-outlook.com/blob/master/Tool.py
from datetime import datetime, timedelta
import json

def run():

    date = datetime.now().strftime("%Y-%m-%d")
    home_team = 'FPX'
    visit_team = 'OMG'
    print('开始请求')
    resp, html = Read_URL('https://bifen.qiumibao.com/json/' +
        date + '/list.htm')
    matches = matchName(html, home_team, visit_team)
    if matches:
        print(f'{date} : {matches}')
    else:
        print(f'{date} 没有数据')

    if not matches:
        allData = selectAll(home_team, visit_team)
        if allData:
            print('问问对方是否需要 再考虑是否存入数据库: ')
            print('allData: ', allData)
        else:
            # 啥都没有
            print('啥都没有: ')

def selectAll(home_team, visit_team):
    print('开始查询前15天的')
    allData = []
    for i in range(1, 16):
        resp, html = Read_URL('https://bifen.qiumibao.com/json/' +
            get_date(i) + '/list.htm')
        matches = matchName(html, home_team, visit_team)
        if matches:
            allData.append(matches)
        print(f'{get_date(i)} : {matches if matches else "没有"}')
    return allData

def get_date(days=0):
    date_time = (datetime.now() - timedelta(days=days)).strftime("%Y-%m-%d")
    return date_time

def matchName(html, home_team, visit_team):
    if not html:
        return
    source = json.loads(html)['list']
    prefix = 'https://www.zhibo8.cc'
    matches = []
    for item in source:
        if item['home_team'] == home_team and item['visit_team'] == visit_team:
            url = item['url']
            matches.append(prefix+url.split(".")[0]+'-jijin.htm')
            matches.append(prefix+url.split(".")[0]+'-luxiang.htm')
    return matches

run()
4年前 评论
wangchunbo

@Jason990420 我去,规则又改了啊可能。每周改一次,我也是服气。。。。

4年前 评论
Jason990420

https://www.zhibo8.cc/ 直接点进去, 也是这样, 不知是我这的问题, 还是网站问题

4年前 评论
wangchunbo

@Jason990420 我看了一下,貌似是你的问题啊。。。。

4年前 评论
Jason990420

可能是国外不给连线吧

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
司机 @ 欣昊玉
文章
273
粉丝
339
喜欢
557
收藏
1104
排名:64
访问:12.2 万
私信
所有博文
社区赞助商