xml地图|网站地图|网站标签 [设为首页] [加入收藏]
Python中何时使用断言,的DataTable操作方法
分类:编程

requests: 练手 雪qiu网

 

 1 import requests
 2 import json
 3 import re
 4 import pymysql
 5 url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id=-1&count=10&category=-1'
 6 headers = {
 7     'Cookie': 'aliyungf_tc=AQAAALoQF3p02gsAUhVFebQ3uBBNZn+H; xq_a_token=584d0cf8d5a5a9809761f2244d8d272bac729ed4; xq_a_token.sig=x0gT9jm6qnwd-ddLu66T3A8KiVA; xq_r_token=98f278457fc4e1e5eb0846e36a7296e642b8138a; xq_r_token.sig=2Uxv_DgYTcCjz7qx4j570JpNHIs; _ga=GA1.2.516718356.1534295265; _gid=GA1.2.1050085592.1534295265; u=301534295266356; device_id=f5c21e143ce8060c74a2de7cbcddf0b8; Hm_lvt_1db88642e346389874251b5a1eded6e3=1534295265,1534295722; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1534295722',
 8     'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36',
 9 }
10 res = requests.get(url, headers=headers) #get请求,将url和头文件一并传入
11 response = res.content.decode('utf-8')  # content 和 request下的.read()作用是一样的
12 response = json.loads(response)#分析第一个页面 从第一个页面中提取下一个Ajax请求所需要的id
13 while True:
14     if response['next_id'] != None:
15         url = 'https://xueqiu.com/v4/statuses/public_timeline_by_category.json?since_id=-1&max_id={}&count=15&category=-1'
16         fullurl = url.format(response['next_id']) #通过上面获取的id将需要浏览的下一个网页的url进行补全
17         res = requests.get(fullurl, headers=headers)
18         response = res.content.decode('utf-8')
19         response = json.loads(response) #response是个字典
20         # print(response)
21         ans_text = response['list']
22         # print(type(ans_text)) #list
23         for i in ans_text:
24             #i是字典
25             rul  = re.compile(r'"topic_title":"(.*?)",') #通过正则将需要的数据提取出来
26             rul2 = re.compile(r'"description":"(.*?)",')
27             ans1 = rul.findall(i['data'])
28             ans2 = rul2.findall(i['data'])
29             print(ans1)  #type 为list
30             print(ans2)
31             print('-' * 50)
32             
33             #将数据存到数据库中
34             connection = pymysql.connect(host='localhost',user='root',password='1234',db='xq')
35         try:
36             with connection.cursor() as cursor:
37                 # Create a new record
38                 sql = "INSERT INTO `xq_info` (`title`, `info`) VALUES (%s, %s)"
39                 cursor.execute(sql, (ans1[0],ans2[0]))
40             connection.commit()
41         finally:
42             connection.close()
43         print('&'*50)
44     else:
45         break

 

 

1.将泛型集合类转变到DataTable(表中无数据时使用):

 

  public static DataTable NullListToDataTable(IList list)
        {
            var result = new DataTable();
            if (list.Count <= 0) return result;
            var propertys = list[0].GetType().GetProperties();
            foreach (var pi in propertys)
            {
                if (pi != null)
                {
                    result.Columns.Add(pi.Name, pi.PropertyType);
                }
            }
            for (var i = 0; i < list.Count; i++)
            {
                var tempList = new ArrayList();
                foreach (var pi in propertys)
                {
                    var obj = pi.GetValue(list[i], null);
                    tempList.Add(obj);
                }
                var array = tempList.ToArray();
                result.LoadDataRow(array, true);
            }
            return result;
        }

 

2.将泛型集合类调换到DataTable(表中有数量时行使):

使用断言的最好机会一时会被聊起,日常是因为有人误用,由此小编感觉有不可紧缺写风姿浪漫篇作品来论述一下怎么时候应该用断言,为何应该用,何时不应该用。

 public static DataTable NoNullListToDataTable<T>(IList<T> list)
        {
            var ds = new DataSet();
            var dt = new DataTable(typeof(T).Name);
            var myPropertyInfo =
                typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var t in list)
            {
                if (t == null) continue;
                var row = dt.NewRow();
                for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                {
                    var pi = myPropertyInfo[i];
                    var name = pi.Name;
                    if (dt.Columns[name] != null) continue;
                    DataColumn column;
                    if (pi.PropertyType.UnderlyingSystemType.ToString() == "System.Nullable`1[System.Int32]")
                    {
                        column = new DataColumn(name, typeof(int));
                        dt.Columns.Add(column);
                        if (pi.GetValue(t, null) != null)
                            row[name] = pi.GetValue(t, null);
                        else
                            row[name] = DBNull.Value;
                    }
                    else
                    {
                        column = new DataColumn(name, pi.PropertyType);
                        dt.Columns.Add(column);
                        row[name] = pi.GetValue(t, null);
                    }
                }
                dt.Rows.Add(row);
            }
            ds.Tables.Add(dt);
            return ds.Tables[0];
        }

对那一个并未开采到用断言的最棒机遇的人来讲,Python的断言正是检查测量检验三个原则,假使条件为真,它怎么都不做;反之它触发四个带可选错误新闻的AssertionError。如下例所示:

3.表中有多少或无数据时使用,可衰亡DATASET不帮忙System.Nullable错误:

图片 1

 public static DataTable ToDataTable<T>(IList<T> list)
        {
            if (list == null || list.Count <= 0)
            {
                var result = new DataTable();
                object temp;
                if (list == null || list.Count <= 0) return result;
                var propertys = list[0].GetType().GetProperties();
                foreach (var pi in propertys)
                {
                    {
                        result.Columns.Add(pi.Name, pi.PropertyType);
                    }
                }
                for (var i = 0; i < list.Count; i++)
                {
                    var tempList = new ArrayList();
                    foreach (var pi in propertys)
                    {
                        var obj = pi.GetValue(list[i], null);
                        tempList.Add(obj);
                    }
                    var array = tempList.ToArray();
                    result.LoadDataRow(array, true);
                }
                return result;
            }
            var ds = new DataSet();
            var dt = new DataTable(typeof(T).Name);
            var myPropertyInfo =
                typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var t in list)
            {
                if (t == null) continue;
                var row = dt.NewRow();
                for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
                {
                    var pi = myPropertyInfo[i];
                    var name = pi.Name;
                    if (dt.Columns[name] != null) continue;
                    DataColumn column;
                    if (pi.PropertyType.UnderlyingSystemType.ToString() == "System.Nullable`1[System.Int32]")
                    {
                        column = new DataColumn(name, typeof(int));
                        dt.Columns.Add(column);
                        if (pi.GetValue(t, null) != null)
                            row[name] = pi.GetValue(t, null);
                        else
                            row[name] = DBNull.Value;
                    }
                    else
                    {
                        column = new DataColumn(name, pi.PropertyType);
                        dt.Columns.Add(column);
                        row[name] = pi.GetValue(t, null);
                    }
                }
                dt.Rows.Add(row);
            }
            ds.Tables.Add(dt);
            return ds.Tables[0];
        }

比非常多个人将断言作为当传递了不当的参数值时的风姿洒脱种高效而方便的触及万分的办法。但实在这里是荒诞的,何况是拾分危殆的谬误,原因有两点。首先,AssertionError平时是在测量检验函数参数时交由的大错特错。你不会像上面那样编码:

4.联结相符的DataTable:

图片 2

   public static DataTable MergeSameDatatable(DataTable dataTable1, DataTable dataTable2)
        {
            var newDataTable = dataTable1.Clone();
            var obj = new object[newDataTable.Columns.Count];
            for (var i = 0; i < dataTable1.Rows.Count; i++)
            {
                dataTable1.Rows[i].ItemArray.CopyTo(obj, 0);
                newDataTable.Rows.Add(obj);
            }
            for (var i = 0; i < dataTable2.Rows.Count; i++)
            {
                dataTable2.Rows[i].ItemArray.CopyTo(obj, 0);
                newDataTable.Rows.Add(obj);
            }
            return new DataTable();
        }

你应有用TypeError来代替,“断言”化解了不当的丰裕类型。

5.将五个列差异的DataTable合併成二个新的DataTable :

本文由澳门新葡亰手机版发布于编程,转载请注明出处:Python中何时使用断言,的DataTable操作方法

上一篇:文件相同性判断,预处理器 下一篇:没有了
猜你喜欢
热门排行
精彩图文