python3.6爬取网易彩票并存储在dataframe中

本文介绍了一款用于爬取网易彩票网站上双色球历史数据的Python爬虫程序。该程序利用BeautifulSoup进行网页解析,并通过Pandas库将获取的数据整理成DataFrame格式,便于进一步分析。覆盖了从2004年至指定年份的数据抓取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

添加引用

import urllib.request
import urllib.parse
import numpy as np
import http.cookiejar
import pandas as pd
from bs4 import BeautifulSoup
from pandas import DataFrame

主函数

def doubleChromosphereWy():
    data=getYear()
    #print(data)
    header=titles('http://trend.caipiao.163.com/ssq/?year=2004')
    print(len(data))
    print(len(header))
    pd.set_option('max_rows',len(data))
    pd.set_option('max_columns',len(header))
    df=pd.DataFrame(data,columns=header)
    print(df)

定义DataFrame的header

def titles(url):
    html = getHtml(url)
    soup = BeautifulSoup(html, 'html.parser')
    # 列名
    thead = soup.table.thead.tr.stripped_strings
    column_list = []
    for th in thead:
        column_list.append(th)
    return column_list

爬取数据

def getYear():
    list_years = [2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018]
    #list_years = [2004,2005]
    data=[]
    for item in list_years:
       data+=wangyi(item)
    return data

def wangyi(year):
    url='http://trend.caipiao.163.com/ssq/?year='+str(year)
    html = getHtml(url)
    soup = BeautifulSoup(html, 'html.parser')
    #单元格内容
    tr=soup.table.tbody.find_all('tr')
    data_list=[]
    for data in tr:
        idata=data.get('data-period')
        bull=[int(idata)]
        for item in data.find_all('td'):
            foldcolor=item.get('class')
           #红球
            if foldcolor==['f_red'] or foldcolor == ['f_blue']:
                 # print('0')
                  bull.append(0)
            if foldcolor==['ball_brown']or foldcolor==['ball_red'] or foldcolor==['ball_blue', 'js-fold']:
                 # print(item.get_text())
                  bull.append(int(item.get_text()))
        data_list.append(bull)
    #print(data_list)
    return data_list

爬取函数

def getHtml(url):
    cj=http.cookiejar.CookieJar()
    opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
    opener.addheaders = [('User-Agent',
                          'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36'),
                         ]
    urllib.request.install_opener(opener)
    html_bytes=urllib.request.urlopen(url).read()
    html_string=html_bytes.decode('utf-8')
    return html_string
Python中,我们可以使用`requests`库获取网页内容,`BeautifulSoup`库解析HTML,然后通过`pandas`库将数据存储到Excel文件中。这里是一个基本示例,展示如何爬取网易云课堂的课程列表将其保存为xlsx文件: ```python import requests from bs4 import BeautifulSoup import pandas as pd # 网易云课堂课程列表URL url = "https://class.163.com/" def get_course_data(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 解析数据部分可能会有所不同,这里假设课程信息在class="course-item"标签内 courses = soup.find_all('div', class_='course-item') data = [] for course in courses: title = course.find('h3').text.strip() # 课程标题 link = course.find('a')['href'] # 课程链接 instructor = course.find('span', class_='author-name').text.strip() # 导师名 data.append({'Title': title, 'Link': link, 'Instructor': instructor}) return data def save_to_excel(data, filename): df = pd.DataFrame(data) df.to_excel(filename, index=False) courses = get_course_data(url) save_to_excel(courses, '网易云课堂课程.xlsx') ``` 这个脚本首先请求课程列表页面,然后使用BeautifulSoup解析出课程标题、链接和导师姓名。所有这些信息都被添加到一个字典列表中,最后转换成pandas DataFrame保存为Excel文件。 请注意,实际操作时,你需要根据网易云课堂的网页结构调整`find`和`find_all`函数中的标签选择器。此外,某些网站可能有反爬机制,如需要模拟用户行为、设置headers、处理验证码等,请根据实际情况进一步完善。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tskpcp

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值