用python写爬虫demo

本文介绍了一次使用Python进行网络爬虫的实践,通过requests和BeautifulSoup库抓取网易股票网站的数据。代码包含在StaticStock.py和DynamicStock.py文件中,详细注释便于理解。

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

python真的特别适合处理字符串

而且python有大量的库,如用来处理网页的requests和 BeautifulSoup 库

这次demo是用python爬取网易的股票网站

http://quotes.money.163.com/

直接上代码,里面的注释很详细。

代码在这里:点击打开链接

代码:

StaticStock.py

import requests
import re
from bs4 import BeautifulSoup

####   第一题   ######################################
#调用requests来爬取网页
url = 'http://quotes.money.163.com/0600795.html'#定义url
res = requests.get(url)
res.encoding = "utf-8"  # 设置网页编码
# 字符串处理,得到   0600795.html
filename = url.split('/')[-1]
#保存网页
fd = open(filename, 'w', encoding='utf-8', errors='ignore')
print(res.text, file=fd)
fd.close()
##########    第二题   ###########################
##调用BeautifulSoup来处理网页
soup = BeautifulSoup(open(filename, encoding='utf-8'), "html.parser")
##找到类名为 corp_info 的table
tag1 = soup.select(".corp_info")
ch = []
for child in tag1[0].strings:
    ch.append(child)
##正则匹配,得到日期
mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2})", (ch[19]))
##输出日期
print('这一只股票首次上市的时间:\n',mat.group())
#############   第三题       ################################
##调用requests来爬取网页
url = 'http://quotes.money.163.com/trade/lsjysj_600795.html?year=2016&season=1'
res = requests.get(url)
res.encoding = "utf-8"  # 设置网页编码
##正则表达式得到股票代号  年   季度
filename = url.split('/')[-1].split('?')
tem = filename[1].split('&')
##正则匹配
mat = re.search(r"(\d+)", (filename[0]))
##no  股票代号
no = mat.group()

mat = re.search(r"(\d+)", (tem[0]))
##year  年
year = mat.group()
mat = re.search(r"(\d+)", (tem[1]))
##season  季度
season = mat.group()
# print('year:',year,'\nsession',session,'\nno',no)
#根据题目要求,将这些分别连接起来,组成filename
filename = no + '_' + year + '_' + season + '.html'
##将数据存入文件
fd=open(filename,'w',encoding='utf-8',errors='ignore')
print(res.text,file=fd)
fd.close()
##调用BeautifulSoup来处理网页
soup = BeautifulSoup(open(filename, encoding='utf-8'), "html.parser")
##利用class得到表格及其内容
table = soup.select(".table_bg001")[0]
table_child = table.children
table_content = [i for i in table_child]
##根据特征,所有tr都大于200,所以可以根据这个特点,将需要的数据摘出来

list_tr = [i for i in table_content if len(str(i)) > 200]
##将子节点全部取出来,每一个tr就是一条数据
tr = [[i for i in list_tr[j].strings] for j in range(len(list_tr))]
#print(tr)
##利用列表解析和切片,得到规定要求的数据格式
dataPerTime = [(i[0], tuple(i[1:])) for i in tr]

import pickle
##将最后得到的数据有pickle保存,用eval还原即可使用
fd = open('./dataPerTime.txt', 'wb')
pickle.dump(str(dataPerTime), fd)
fd.close()
#########   第四题   #################################################################3
##循环读入,直到-1结束
##然后会在命令行输出想要的排序结果
key=int(input("请输入你想要的排序顺序:\n1:以日期为序\n2:以成交量为序\n3:以成交金额为序\n.......\n如果没有其他需求,-1结束\n"))
#当输入一个数,且不是-1
while(key!=-1):

#处理边界
    if(key>11):#上界
        key=1
    if(key<-1 or key==0):#下界
        key=1
    ###根据输入的值,进行排序
    dataSort=sorted(tr,key=lambda x:x[key-1])
    ##按照规定格式进行输出
    dataPerTimeSort = [(i[0], tuple(i[1:])) for i in dataSort]
    for item in dataPerTimeSort:
        print(item)
    key=int(input("请输入你想要的排序顺序:\n1:以日期为序\n2:以成交量为序\n3:以成交金额为序\n.......\n如果没有其他需求,-1结束\n"))

DynamicStock.py

import requests
import  re
#from requests.exceptions import ConnectionError
from bs4 import BeautifulSoup
####           第六题   ################################################
##循环输入,直到-1结束
key=int(input("请输入你想要的查询的股票代码:如果没有其他需求,-1结束\n"))
while(key!=-1):
    ##根据输入,组合url
    url='http://quotes.money.163.com/0'+str(key)+'.html'
    #try:
    ##获取网页内容
    res = requests.get(url)
    res.encoding = "utf-8"  # 设置网页编码
    #print(r.status_code)
    ##如果股票代码错误,那么将会提示找不到,需要重新输入
    if(res.status_code==404):
        key = int(input("你输入的股票代码查询不到,请重新输入,如果没有其他需求,-1结束\n"))
        #continue可以直接结束下面的内容,跳转到while
        continue
    # 用bs4处理网页结构
    soup = BeautifulSoup(res.text, "html.parser")
    table = soup.select(".corp_info")
    table_child = []

    for child in table[0].strings:
        table_child.append(child)
    ##用正则表达式找到“上市日期”
    mat = re.search(r"(\d{4}-\d{1,2}-\d{1,2})", (table_child[19]))
    print('首次上市的时间:\n',mat.group())#
    date=mat.group()
    mat = re.search(r"(\d+)", (date))
    ##得到 year
    year = int(mat.group())

    ##将得到的数据都保存到txt中,用excel打开
    filename = './txt/'+str(key)+'.txt'
    fd = open(filename, 'w', encoding='utf-8', errors='ignore')
    print('正在下载,请稍等')
    ##做循环,year和season的二重循环,将所有数据得到
    while(year<=2017):
        #print('year:   ',year)
        for season  in  range(1,5):
            #print('season:   ', season)
            #得到url
            newUrl = 'http://quotes.money.163.com/trade/lsjysj_'+str(key)+'.html?year='+str(year)+'&season='+str(season)
            #print(newUrl)
            #得到网页内容
            newRes = requests.get(newUrl)
            newRes.encoding = "utf-8"  # 设置网页编码
            ##处理网页结构
            soup = BeautifulSoup(newRes.text, "html.parser")
            ##找到有数据的table
            table_data = soup.select(".table_bg001")[0]
            #print("table_data:    ",table_data)

            table_data_child = table_data.children
            tchild = [i for i in table_data_child]
            ####根据特征,所有tr都大于200,所以可以根据这个特点,将需要的数据摘出来
            list_tr = [i for i in tchild if len(str(i)) > 200]
            ##将子节点全部取出来,每一个tr就是一条数据
            tr = [[i for i in list_tr[j].strings] for j in range(len(list_tr))]
            ###将每一条数据都输入到文本中,以\t分割
            for dataPerTime in tr:
                for ind in range(len(dataPerTime)):
                    print(dataPerTime[ind],file=fd,end='\t')

                print(file=fd,end='\n')
        ##year累计,直到2017
        year+=1
    fd.close()
    #600795
    #1997 - 03 - 18
    #print(r.text)
    print('你需要的数据已经存入')
    key = int(input("请输入你想要的查询的股票代码:如果没有其他需求,-1结束\n"))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值