第二次作业

作业1

作业①:

要求:在中国气象网(http://www.weather.com.cn)给定城市集的7日天气预报,并保存在数据库。

输出信息:

序号 地区 日期 天气信息 温度
1 北京 7日(今天) 晴间多云,北部山区有阵雨或雷阵雨转晴转多云 31℃/17℃
2 北京 8日(明天) 多云转晴,北部地区有分散阵雨或雷阵雨转晴 34℃/20℃
3 北京 9日(后台) 晴转多云 36℃/22℃
4 北京 10日(周六) 阴转阵雨 30℃/19℃
5 北京 11日(周日) 阵雨 27℃/18℃
6......

(1)代码如下:


# -*- coding = utf-8 -*-
# @Time:2020/9/30 8:54
# @Author:CaoLanying
# @File:stock.py
# @Software:PyCharm
from bs4 import BeautifulSoup
from bs4 import UnicodeDammit
import urllib.request
import sqlite3

class WeatherDB:
    def openDB(self):
        self.con=sqlite3.connect("weathers.db")
        self.cursor=self.con.cursor()
        try:
            self.cursor.execute("create table weathers (wCity varchar(16),wDate varchar(16),wWeather varchar(64),wTemp varchar(32),constraint pk_weather primary key (wCity,wDate))")
        except:
            self.cursor.execute("delete from weathers")

    def closeDB(self):
        self.con.commit()
        self.con.close()

    def insert(self, city, date, weather, temp):
        try:
            self.cursor.execute("insert into weathers (wCity,wDate,wWeather,wTemp) values (?,?,?,?)",
                                (city, date, weather, temp))
        except Exception as err:
            print(err)



def show(self):
    self.cursor.execute("select * from weathers")
    rows = self.cursor.fetchall()
    print("%-16s%-16s%-32s%-16s" % ("city", "date", "weather", "temp"))
    for row in rows:
        print("%-16s%-16s%-32s%-16s" % (row[0], row[1], row[2], row[3]))



class WeatherForecast:
    def __init__(self):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 6.0 x64; en-US; rv:1.9pre) Gecko/2008072421 Minefield/3.0.2pre"}
        self.cityCode = {"北京": "101010100", "上海": "101020100", "广州": "101280101", "深圳": "101280601"}

    def forecastCity(self, city):
        if city not in self.cityCode.keys():
            print(city + " code cannot be found")
            return


        url = "http://www.weather.com.cn/weather/" + self.cityCode[city] + ".shtml"
        try:
            req = urllib.request.Request(url, headers=self.headers)
            data = urllib.request.urlopen(req)
            data = data.read()
            dammit = UnicodeDammit(data, ["utf-8", "gbk"])
            data = dammit.unicode_markup
            soup = BeautifulSoup(data, "html.parser")
            lis = soup.select("ul[class='t clearfix'] li")
            for li in lis:
                try:
                    date=li.select('h1')[0].text
                    weather=li.select('p[class="wea"]')[0].text
                    temp=li.select('p[class="tem"] span')[0].text+"/"+li.select('p[class="tem"] i')[0].text
                    print(city,date,weather,temp)
                    self.db.insert(city,date,weather,temp)
                except Exception as err:
                        print(err)
        except Exception as err:
                        print(err)


    def process(self, cities):
        self.db = WeatherDB()
        self.db.openDB()


        for city in cities:
            self.forecastCity(city)

            # self.db.show()
        self.db.closeDB()

ws = WeatherForecast()
ws.process(["北京", "上海", "广州", "深圳"])
print("completed")

(2)结果图片:

(3)心得体会:

按着书本上的代码复现了一遍,没什么错误,结果能正确运行。

作业2

要求:用requests和BeautifulSoup库方法定向爬取股票相关信息。

候选网站:东方财富网:https://www.eastmoney.com/

​ 新浪股票:http://finance.sina.com.cn/stock/

技巧:在谷歌浏览器中进入F12调试模式进行抓包,查找股票列表加载使用的url,并分析api返回的值,并根据所要求的参数可适当更改api的请求参数。根据URL可观察请求的参数f1、f2可获取不同的数值,根据情况可删减请求的参数。

参考链接:https://zhuanlan.zhihu.com/p/50099084

输出信息:

序号 股票代码 股票名称 最新报价 涨跌幅 涨跌额 成交量 成交额 振幅 最高 最低 今开 昨收
1 688093 N世华 28.47 62.22% 10.92 26.13万 7.6亿 22.34 32.0 28.08 30.2 17.55
2......

(1)代码如下:


# -*- coding = utf-8 -*-
# @Time:2020/9/30 11:36
# @Author:CaoLanying
# @File:cly_of_171809061.py
# @Software:PyCharm
import requests
import json


def find(url2,str1):

   
    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3775.400 QQBrowser/10.6.4209.400"
    }

    reponse = requests.get(url2,headers=header)
    result = reponse.text
    #result = result.replace('''jQuery112406817237975028352_1601466960670(''',"").replace(');','')#最外层的“);”要去掉,不然一直报错。搞了好久
    result = result.replace(str1, "").replace(');', '')
    result = json.loads(result) #	将已编码的 JSON 字符串解码为 Python 对象

    i = 0 #序号
    print("序号\t","代码\t","名称\t","最新价(元)\t ","涨跌幅 (%)\t",end="")
    print("跌涨额(元)\t", "成交量\t","成交额(元)\t","涨幅(%)\t")
    for f in result['data']['diff']: #遍历输出json里面的内容,有点像数组的遍历
        i += 1
        print(str(i)+"\t",f['f12']+"\t",f['f14']+"\t",str(f['f2'])+"\t",str(f['f3'])+"%\t",str(f['f4'])+"\t",str(f['f5'])+"\t",str(f['f6'])+"\t",str(f['f7'])+"%")





def main():

    url  = "http://75.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112406817237975028352_1601466960670&pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1601466960895"
    str1 = '''jQuery112406817237975028352_1601466960670('''
    find(url,str1)
    url = "http://25.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112405946510903534898_1601697861791&pn=2&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1601697861989"
    str1 = '''jQuery112405946510903534898_1601697861791('''
    find(url,str1)

if __name__ == '__main__':
    main()

(2)结果图片:

(3)心得体会:


爬取动态网页的数据,又因为数据格式是js的,所以看到书本上有json包,想着要用这个方法来解决问题。json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构。过程中困扰我最多的是,.downloads()没办法使用。这是因为抓下来的数据格式有问题,它比正常的文件多了一点内容,不能正确解析为json文件。所以要去掉多余数据。接下来,我又研究怎么才能把json对象里面的数据提取出来。查了网上的资料,发现要提数据还是挺简单的,就像遍历数组一样,非常方便。但是,没有抓取很多页。

作业3

要求:根据自选3位数+学号后3位选取股票,获取印股票信息。抓包方法同作②。

候选网站:东方财富网:https://www.eastmoney.com/

​ 新浪股票:http://finance.sina.com.cn/stock/

输出信息:

股票代码号 股票名称 今日开 今日最高 今日最低
605006 山东玻纤 9.04 8,58 8.13

**

(1)代码如下:
**


import requests
import json

def find(url2,str1):

    header = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3775.400 QQBrowser/10.6.4209.400"
    }

    reponse = requests.get(url2, headers=header)
    result = reponse.text
    result = result.replace(str1, "").replace(');', '')
    result = json.loads(result)

    i = 0
    print("代码\t", "名称\t", "今日开" + "\t ", "今日最高\t", "今日最低")
    for f in result['data']['diff']:
        i += 1
        if(str(f['f12']).endswith("061")): #选取以我学号171809061后三位061结尾的股票
            print(f['f12'] + "\t",f['f14'] + "\t", str(f['f17']) + "\t",str(f['f2'])+ "\t", str(f['f16'])+ "\t")


def main():

    url  = "http://25.push2.eastmoney.com/api/qt/clist/get?cb=jQuery112405946510903534898_1601697861791&pn=9&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152&_=1601697862060"
    str1 = '''jQuery112405946510903534898_1601697861791('''
    find(url,str1)

if __name__ == '__main__':
    main()


**

(2)结果图片:
**

(3)心得体会:


做了第二个作业会发现这个作业还挺简单,只需要在上一个作业的基础上加一点东西就好,我发现以我学号结尾的股票还是很少的,两三页才能遇上一个。

posted @   朝南烟  阅读(388)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
body { color: #000; background-color: #e6e6e6; font-family: "Helvetica Neue",Helvetica,Verdana,Arial,sans-serif; font-size: 12px; min-height: 101%; background: url(https://images.cnblogs.com/cnblogs_com/caolanying/1841633/o_2009041…ly1geq8oc9owbj21hc0u0th5.jpg) fixed; } #home { margin: 0 auto; opacity: 0.8; width: 65%; min-width: 1080px; background-color: #fff; padding: 30px; margin-top: 50px; margin-bottom: 50px; box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3); }
点击右上角即可分享
微信分享提示