Python抓大乐透和双色球号码

最近一直买大乐透和双色球,就想着抓取近几年的大乐透和双色球数据,找到网上Demo学习,下面开始教程:
工具:python3 pip3 安装requests-html
电脑:MacBook

import requests
from requests.exceptions import RequestException
from lxml import etree
count = 0
f = open('/Volumes/TF/daletoutest.txt', 'a+')
f.seek(0)


def main(num):
    url = 'http://caipiao.163.com/t/award/dlt/{}.html'.format(str(num))
    html = get_page(url)
    parse_page(html,num)


def get_page(url):
    try:
        headers = {
            'user-agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Mobile Safari/537.36',
            'accept-language': 'zh-CN,zh;q=0.9',
            'cache-control': 'max-age=0',
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
        }
        response = requests.get(url=url, headers=headers)
        # 更改编码方式,否则会出现乱码的情况
        response.encoding = "utf-8"
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        return None


def parse_page(html,num):
    try:
        global count
        count += 1
        res = etree.HTML(html)
        red = res.xpath('//*[@class="smallRedball"]//text()')
        blue = res.xpath('//*[@class="smallBlueball"]//text()')

        line = str(num)+str(red) + str(blue) + "\n"
        f.write(line)
        print(red + blue)

    except Exception as e:
        pass


if __name__ == '__main__':
    for num in range(14001, 14154):
        main(num)
    for num in range(15001, 15153):
        main(num)
    for num in range(16001, 16154):
        main(num)
    for num in range(17001, 17153):
        main(num)
    for num in range(18001, 18154):
        main(num)
    for num in range(19001, 19009):
        main(num)
    f.close()
    print("爬取的数目为:" + str(count))

最后会按照路径保存为txt文件,然后通过修改为cvs文件,可以导入到mysql和sqlserver.

//双色球的url为:‘http://caipiao.163.com/t/award/ssq/{}.html’ 同时num修改为=2014001到2014153即可

你可能感兴趣的:(Python)