学习总结(截止2019-3-13)

2019-3-13

目前进度,已可以将处理信息存入es,具体代码如下:

def b_job():
    for page_i in range(1,2):
        def a_job():
            return get_res(page_i)
        res = retry_job(a_job,60)
    return res

outcome=b_job()

es = Elasticsearch(hosts='192.168.31.9:9200')
es_bhv = HjEsIO(es=es)

for data in key_value_list:
    es_bhv.create_and_upload(index_name='bond',data=data)

待解决问题,如何实现定时执行功能

当前思路:
1 获取当前时间,与定时时间比较
2 如相差大于a小时,则睡眠a小时后执行
3 如相差小于1小时大于b分钟,则休眠b分钟后执行
4 如相差小于1分钟,则睡眠1秒后执行
卡点,时间为str格式不方便直接比较,也不能转为int和float格式。

2019-3-11

答疑

目前进度,字段信息已取出,在处理把信息存入es阶段。
问题

1 如何在把字段信息存入es时,以字段名命名,字段信息如下:

entyDefinedCode': '305888', 'issueEndDate': '2019-03-28', 'bondDefinedCode': '6498280024', 'issueStartDate': '2019-03-22', 'entyFullName': '四川阆中农村商业银行股份有限公司', 'debtRtng': '---', 'bondType': '大额存单', 'bondTypeCode': '100058', 'bondName': '阆中农商银行2019年第5期个人大额存单3Y', 'bondCode': '1906280024'

2 查了下 定时重爬是否通过以下代码实现?
 while True:
        print(time.strftime('%Y-%m-%d %X',time.localtime()))
        b_job()
        time.sleep(5)

2019-3-7

答疑

不好意思,这两天有点忙,哈哈。函数里怎么取出结果呢,比如下面函数要取出res的最终值?

def b_job():
    for page_i in range(1,10):
        def a_job():
            return get_res(page_i)
        res = retry_job(a_job,60)

2019-3-5

答疑

这样呢

def a_job(page_i):
    print(page_i)
    data = {'pageNo': page_i, 'pageSize': '15'}
    page_source = requests.post(url1, data=data,headers=headers).content.decode(encoding='utf-8', errors='ignore')
    page_json = json.loads(page_source)
    data_list=page_json['data']['resultList']
    key_value_list.extend(data_list)
    frm = pd.DataFrame(key_value_list[0], index=[0])
    return frm


def retry_job(a_job, sleep_time):
    while 1:
        try:
            return(a_job())
        except:
            time.sleep(sleep_time)

def b_job():
    for page_i in range(1,10):
        res = retry_job(a_job,60)

答疑

求指导,问题出在哪?并且这样会跳过出错页吗?

def a_job(page_i):
    print(page_i)
    data = {'pageNo': page_i, 'pageSize': '15'}
    page_source = requests.post(url1, data=data,headers=headers).content.decode(encoding='utf-8', errors='ignore')
    page_json = json.loads(page_source)
    data_list=page_json['data']['resultList']
    key_value_list.extend(data_list)
    return(key_value_list)


def retry_job(a_job, sleep_time):
        for page_i in range(1,100):
            while 1:
                try:
                    return a_job(page_i)
                except:
                    time.sleep(sleep_time)

2019-3-3

答疑

已根据提示编写语句,提示
image.png

,无法查出return错误在哪,具体代码如下:


image.png

2019-2-20

解题过程

url1 = r'http://www.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoList2'
key_value_list=[]
for page_i in range(1,11):
    try:
        print(page_i)
        data = {'pageNo': page_i, 'pageSize': '15'}
        page_source = requests.post(url1, data=data,headers=headers).content.decode(encoding='utf-8', errors='ignore')
        page_json = json.loads(page_source)
        data_list=page_json['data']['resultList']
        key_value_list.extend(data_list)
    except:
        time.sleep(60)
        page_i=-1
frm=pd.DataFrame(key_value_list[0],index=[0])
for key_value in key_value_list[1:]:
    frm = frm.append(pd.DataFrame(key_value,index=[0]),ignore_index=True)

2019-2-19

解题文字思路

代码还不知如何实现断点重连,先记录下文字思路

在request.post.........代码下加上
if 遇到post请求失败的情况①:则 sleep 60秒 后重新执行上一步骤②
else:运行正常步骤

如思路可行,那么①和②的具体实行代码是?

2019-2-15

解题结果及过程

image.png
headers = {
'Accept': 'application/json, text/javascript, */*; q=0.01',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'no-cache',
'Content-Length': '111',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Cookie': '_ulta_id.CM-Prod.e9dc=d8a40698afc88ac2; _ulta_ses.CM-Prod.e9dc=65eb9b4c1557b1e7; A9qF0lbkGa=MDAwM2IyNTRjZDAwMDAwMDAwNGYwGhsQa1gxNTUwMjE5NzQ3; JSESSIONID=JbfulNwClqSdk3XtHxbjKmNbnfILjAfTrSiS_RnYsdyMmUJcyYBB!2102842532',
'Host': 'www.chinamoney.com.cn',
'Origin': 'http://www.chinamoney.com.cn',
'Pragma': 'no-cache',
'Proxy-Connection': 'keep-alive',
'Referer': 'http://www.chinamoney.com.cn/chinese/qwjsn/?searchValue=%25E6%25B7%25B1%25E9%25AB%2598%25E9%2580%259F',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',
'X-Requested-With':'XMLHttpRequest'
}
url1 = r'http://www.chinamoney.com.cn/ags/ms/cm-u-bond-md/BondMarketInfoList2'
key_value_list=[]
for page_i in range(1,5):
    print(page_i)
    data = {'pageNo': page_i, 'pageSize': '15'}
    page_source = requests.post(url1, data=data,headers=headers).content.decode(encoding='utf-8', errors='ignore')
    page_json = json.loads(page_source)
    data_list=page_json['data']['resultList']
    key_value_list.extend(data_list)
frm=pd.DataFrame(key_value_list[0],index=[0])
for key_value in key_value_list[1:]:
    frm = frm.append(pd.DataFrame(key_value,index=[0]),ignore_index=True)

2019-2-14

答疑

按照request.post的方式添加了data参数,得到的结果还是不对,如图


image.png

image.png

2019-1-30

答疑

按照之前的方法取url,发现无论怎么改变查询页数或者查询条件得到的url地址都是
image.png

若直接用此url来request的话只能获得首页的单一发行人的信息;

另外注意到了有一行form data信息
image.png

不知道是否可以利用这个信息建立与url的联系?

2019-1-24

笔记

思路:找到url结合format遍历页面-----筛选出信息并转为json-----转换成frm并整理-----转换成dict-----逐条存入es中
突破点:
1 通过begin_date end_date选择时间区间;
2 使用frm.to_dict(orient='records')将frm转换成dict;
3 结合for data in frm_dict与index的使用,把每一条的公告信息存入,并且将重复的自然覆盖

begin_date='2019-01-25'
end_date='2019-01-25'
for page_i in range(1,100):
    print(page_i)
    page_source = requests.get(url1.format(page_i,begin_date,end_date), headers=headers).content.decode(encoding='utf-8', errors='ignore')
    res=re.findall('[A-Za-z0-9]\((.*?)\)',page_source)[0]
res_json = json.loads(res)
key_value_list=res_json['pageHelp']['data']
frm=pd.DataFrame(key_value_list[0],index=[0])
for key_value in key_value_list[1:]:
   frm = frm.append(pd.DataFrame(key_value,index=[0]),ignore_index=True)
frm=frm.loc[:,['security_Code','title','URL','SSEDate','bulletin_Type','bulletin_Year']]
frm_dict=frm.to_dict(orient='records')
es = Elasticsearch(hosts='192.168.1.9:9200')
es.indices.create(index='anouncement_ww', ignore=400)
for data in frm_dict:
    es.index(index='anouncement_ww', doc_type='sz', body=data)
result = es.search(index='anouncement_ww', doc_type='sz')
print(result)

答疑

存入es的每一条信息包括{code: , title:,url: 等等 },如何实现在指定index中serch出所有某code的信息?

2019-1-22

答疑

1 之前是把dict存入es,frm可以直接存入es么,尝试了下显示下列报错?


image.png

2 下列将frm里的数据更新到es中的大致逻辑是?

    def update_es_by_frm(self, es, frm, index_name, doc_type=cf.DEFAULT_TYPE, id=None, id_col_name="file_id"):
        """
        [外方]将frm里的数据更新到es中
        :param frm: frm格式存储的数据
        :param host: es地址
        :param doc_type: doc_type:只需保持一致即可
        :param index_name: es的index名
        :param id: id写入方式,默认是row_dict里的file_id
        """
        assert_isinstance([frm, doc_type, index_name], [pd.DataFrame, str, str])
        actions = []
        assert isinstance(frm, pd.DataFrame)
        row_dict_list = frm.to_dict(orient='records')
        if id == None:
            for row_dict in row_dict_list:
                action = {
                    "_index": index_name,
                    "_type": doc_type,
                    "_id": row_dict[id_col_name],
                    "_source": row_dict
                }
                actions.append(action)
        else:
            for row_dict in row_dict_list:
                action = {
                    "_index": index_name,
                    "_type": doc_type,
                    # "_id": row_dict['file_id'],
                    "_source": row_dict
                }
                actions.append(action)
        helpers.bulk(es, actions)

2019-1-21

笔记

result = es.create(index=xxx,doc_type=xxxx,id=xxx)
result = es.delete(index=***, ignore=[400, 404])
result = es.index(index=xxx, doc_type=xxx, body=xxx)
result = es.update(index=xxx, doc_type=xxx, body=xxx, id=xxx)
result = es.search(index=xxx doc_type=xxx)

答疑

针对练习题,直接用es.index的方式把json文件存入es中是否满足题意?

for page_i in range(1,5):
    print(page_i)
    page_source = requests.get(url1.format(page_i), headers=headers).content.decode(encoding='utf-8', errors='ignore')
    res=re.findall('[A-Za-z0-9]\((.*?)\)',page_source)[0]
res_json = json.loads(res)
key_value_list=res_json['pageHelp']['data']
frm1=pd.DataFrame(key_value_list[0],index=[0])

for key_value in key_value_list[1:]:
   frm1 = frm1.append(pd.DataFrame(key_value,index=[0]),ignore_index=True)

es = Elasticsearch(hosts='192.168.1.9:9200')
# es_bhv = HjEsIO(es)
res_es_list = es.index(index=1111, doc_type='d_type',body=key_value,ignore=400)
result = es.search(index=1111, doc_type='d_type')
print(result)

2019-1-18

进度

已完成DateFrame如图


image.png

代码如图:


image.png

笔记

在使用 pandas 的 DataFrame 方法时碰到的一个错误 ValueError: If using all scalar values, you must pass an index。
这是因为 pandas 的 DataFrame 方法需要传入一个可迭代的对象(列表,元组,字典等), 或者给 DataFrame 指定 index 参数就可以解决这个问题,如图


image.png

答疑

为何定义i==0时,i下面会划红线?

2019-1-16

卡点

1 str转json时报错(如下图),目测为str中有数据不符合json格式,如何能快速找到错误?


image.png

2 在有for循环的情况下debug,刚开始debug能在遍历所有区间后显示debug结果;之后的debug在第一个取值后便结束并显示结果,原因是?

2019-1-15

卡点

1 (已解决,通过点击“下一页”“查询”获取)我通过network--xhr取得原始数据并整理得到结果如下图,感觉与题意不相符,是否取错数据(因为没有发现有很多字段),是否应该通过elements获取数据?


image.png

2 插入本地模块时仍会报错,如下图:


image.png

3 翻阅了网上好几篇关于es的使用教程,不是非常理解,有没有通俗易懂易上手的教程?

2019-1-14

进度

今日练习完成了一半,尚未全部完成

答疑

如何修改project路径,使得引用的本地模块生效?


image.png

今日练习中,可以直接取得公告名称,未发现json字符串?

2019-12

笔记

在使用xhr无效时如何查找url,通过all逐项查找。
json.loads 将已编码的 JSON 字符串解码为 Python 对象

答疑

1 from esfrm.es_class import HjEsIO 和 from yhj_tool.req_bhv import ReqBhvBhv需要怎么安装?

2 自己编写update_shanghai时,写了以下代码,发现只能取第1页的信息,不能遍历所有页。

url2=r'http://query.sse.com.cn/security/stock/getStockListData2.do?&jsonCallBack=jsonpCallback99776&isPagination=true&stockCode=&csrcCode=&areaName=&stockType={0}&pageHelp.cacheSize=1&pageHelp.beginPage={1}&pageHelp.pageSize=25&pageHelp.pageNo=2&_=1547295073470'
headers={
    'Accept-Encoding': 'gzip,deflate',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36',
    'Content-Type': 'application/json',
    'Accept': '*/*',
    'Host': 'query.sse.com.cn',
    'Referer': 'http://www.sse.com.cn/assortment/stock/list/share/',
    'Cookie': 'yfx_c_g_u_id_10000042=_ck19011219292018089363771730333; VISITED_COMPANY_CODE=%5B%22600000%22%5D; VISITED_STOCK_CODE=%5B%22600000%22%5D; seecookie=%5B600000%5D%3A%u6D66%u53D1%u94F6%u884C; VISITED_MENU=%5B%229055%22%2C%228528%22%5D; yfx_f_l_v_t_10000042=f_t_1547292560801__r_t_1547292560801__v_t_1547295072921__r_c_0'
}
source_dict={}
for stock_type in ['1','2']:
    for page_i in range(1,1000):
        print(page_i)
        page_source=requests.get(url2.format(stock_type, page_i),headers=headers).content.decode(encoding='utf-8')

3 update_to_es中 res_es_list = es.search(index_name, doc_type='d_type',body=。。。。。, size=10)['hits']['hits']
此时es是空的,为何可以查询?

def update_to_es(source_dict,index_name):
    es = Elasticsearch(hosts='192.168.1.9:9200')
    es_bhv = HjEsIO(es)
    for i,j in source_dict.items():
        print(i,j)
        announce_date = i[0]
        trade_code = i[1]
        res_es_list = es.search(index_name, doc_type='d_type',body={"query": {"bool":{"must":
                                                                                             [{"match": {"announce_date": announce_date}},
                                                                                              {"match": {"trade_code": trade_code}}
                                                                                              ]}}}, size=10)['hits']['hits']

        if res_es_list:
            row = res_es_list[0]['_source']
            new_list = row['short_company_name']
            if j not in new_list:
                new_list.append(j)
                print('出现新字段,已添加到list!')
                print('------------------------')
            row['short_company_name'] = new_list
            es_bhv.write_row_by_id(index_name,id=res_es_list[0]['_id'],data=row)
        else:
            row = {'announce_date': announce_date, 'trade_code':trade_code, 'short_company_name':[j], 'status':100}
            es_bhv.write_row_by_id(index_name, id=None, data=row)

2019-1-10

笔记部分

.*?懒惰匹配 重复任意次 尽可能少得重复

答疑部分

1 如何挑选哪些是需要的headers?

2 为何下列headers在代码中和网页中的稍有差异
网页中:Accept-Language: zh-CN,zh;q=0.9,en;q=0.8 代码中: Accept-Language': 'zh-CN,zh;q=0.9'
网页中:Proxy-Connection: keep-alive 代码中:Connection': 'keep-alive',

3 res1=re.findall('"agdm":"(.?)","agjc":"(.?),',res) 中 ,',res)的第一个,号的含义是?为什么去掉后会直接影响结果?

4 获取信息的实效问题:比如2019-1-10 需要查询2019-1-1的数据,虽然最后输出的结果会显示2019-1-1,但是根据代码得到的数据信息应该还是2019-1-10,如何解决?

2019-1-9

如何获取URL2地址?

找到网页--F12--netework--XHR--name--headers

如何获取连续多页网页信息?

例:url2 = r'http://www.szse.cn/api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=1110&TABKEY=tab{0}&PAGENO={1}&random={2}'

page_source = requests.get(url2.format(stock_type, page_i, random.random()), headers= headers).content.decode(encoding='utf-8', errors='ignore')

关键点:本例中我们 1)需要取得A股和B股的股票代码,选择A股还是B股是由url2中tab后的数字决定;选择页码是由PAGENO=后的数字,这两个位置用{0} {1}表示,并利用format函数将这两个位置由变量替代,达到遍历效果。

答疑

上述例子中url2中random后{2} 位置替换为 random.random()的意义和作用是?

2019-1-8

卡点

不会如何获取连续多页网页信息?

问题

如何获得URL2?
如何获得headers?作用是?
这3行代码的作用是?
sub_dict = {' +': '', 'B': 'B', 'A': 'A'}
for key, value in sub_dict.items():
company_name = re.sub(key, value, company_name)

完整代码如下:

url2 = r'http://www.szse.cn/api/report/ShowReport/data?SHOWTYPE=JSON&CATALOGID=1110&TABKEY=tab{0}&PAGENO={1}&random={2}'
headers = {
        'Accept-Encoding': 'gzip,deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
       'Content-Type': 'application/json',
       'Accept': 'application/json, text/javascript, */*; q=0.01',
       'Host': 'www.szse.cn',
       'Referer': 'http://www.szse.cn/market/stock/list/index.html',
       'X-Request-Type': 'ajax',
       'X-Requested-With': 'XMLHttpRequest',
    }
source_dict = {}
for stock_type in ['2','1']:
        for page_i in range(1,1000):
            print(page_i)
            page_source = requests.get(url2.format(stock_type, page_i, random.random()), headers= headers).content.decode(encoding='utf-8', errors='ignore')
            res = re.findall('"data":\[(.*?)\]', page_source)[int(stock_type) - 1]
            day = re.findall('"subname":"(.*?)",', page_source)[int(stock_type) - 1]
            day = re.sub(' +','',day)
            if day == '':
                break
            if stock_type == '1':
                res1 = re.findall('"agdm":"(.*?)","agjc":"(.*?)",',res)
            else:
                res1 = re.findall('"bgdm":"(.*?)","bgjc":"(.*?)",', res)
            for i in res1:
                # today = datetime.datetime.today()
                today = datetime.datetime.today() - datetime.timedelta(days=1)#需要调整时间
                today_str = today.strftime('%Y-%m-%d')
                if today_str != day:
                    day = today_str
                company_name = i[1]
                sub_dict = {' +': '', 'B': 'B', 'A': 'A'}
                for key, value in sub_dict.items():
                    company_name = re.sub(key, value, company_name)
                source_dict[(day,i[0])] = company_name

2019-1-4

如何使用groupby 配合 agg对数据聚合?

grouped = a_frm.groupby(by='QuestionId') #DataFrame按照某种规律排序,返回的是DataFrameGroupBy结构;
last_status = grouped.agg(lambda x: x.iloc[-1]) #排序后对行名称相同的取最后一行,返回的是DataFrame

对组合复合代码可以采用分步拆解法理解

答疑

习题1805104答案中为何需要写names = locals()?用names ={}是否更合适?

names = locals()
company_names = ['宁沪高速','深高速','四川成渝']
years = [2017,2016,2015]
for i in company_names:
for j in years:
names['%s_%s'%(i,j)] = str(i)+str(j)

2019-1-3

如何在dataframe中插入列?

frm.insert(列位置,‘插入列命名’,插入的列)

如何在dataframe中移除列?

frm.pop(列位置)

答疑(已答)

bb2[2016] = round(bb2.pop(1)/366,2)
这行代码的作用是,新建一列‘2016 ’列, 数据是以‘1’列的数据/366,并用‘2016’列替代‘1’列;代码具体是怎么实现的,代码中每一个参数、函数的功能?
pop 摘出并在原文件中删去,round保留指定位数小数。

2019-1-2

如何找到指定字符的所在列?

for i in frm.index:
if '指定字符' in list(frm.iloc[i]):
column_num = list(frm.iloc[i]).index('指定字符')
break

frm[[0,3]]代表什么?

frm的第0和第3整列。

答疑(已答):

re.findall('(.+?)(高速|公路)',highway)[0][0]中()及[0]的作用??
限制需要匹配到的字符串;获取的第一个匹配的字符串的第一个字符。

percentage = re.findall(r'\((.+)\)', company)[0]中最内层()的作用?
同上。

12-30

如何对dataframe使用函数?

frm.apply(函数)
例如:frm6['16年收入(百万元)'].apply(toyuan) #toyuan是自己设置的函数。

对下列代码是否有其他表现方式frm6=frm5.loc[frm5['高速公路名称'].str.contains('高速|公路')]

有,frm6=frm5[frm5['高速公路名称'].str.contains('高速|公路')] ##筛选出包含某些字段的行。

如何设置一个函数,把参数转换成乘以1000000以后的数字?

def tofloat(x): ##判断参数是否是浮点型
try:
x = float(x)
except TypeError:
x = x
return x
def toyuan(x): ##参数乘以1000000
try:
the_float = float(x)
return the_float * 1000000
except TypeError:
return x

12-29

如何进行edit configuration 设置?

每次run时跳出edit configuration 设置非常麻烦,设置过程如下:file---setting---project interpreter---选择一个py版本---apply---ok 设置完成

如何把代码附近的绿色解释字段去除?

点击图中小虫符号


image.png

如何将DataFrame写入excel?

frm.to_excel('xxx.xlsx',sheet_name='yyy')
frm.read_excel('xxx.xlsx',sheet_name='yyy')
卡点:
frm.to_excel时 显示ImportError: No module named 'openpyxl',已通过安装openpyxl解决!

答疑部分:

frm6=frm4.loc[frm4['高速公路名称'],str.contains('高速|公路')]时 显示AttributeError: type object 'str' has no attribute 'contains'
已解决 把str前的,改成.

12-28(已更新答疑)

两个dataframe有相同的列信息,如何合并?

使用merge合并,newfrm=pd.merge(frm1,frm2,on='相同column的列名称');

当依据2组相同的列信息合并时,newfrm=pd.merge(frm1,frm2,on=['列名称1','列名称2'],how='inner'或‘outer’),inner时只合并两组信息完全一致的部分,outer时会把不一致的部分一起合并,缺失值默认为NaN。

答疑部分

merge合并中 如果how=left或right时代表的意思??
已实验,left表示根据列信息合并时如果不一致,保留第一组的值,第二组的不一致值为nan;right则反之。

远程机pandas引用DataFrame时无效,重新安装pandas也未成功。
已答疑,import某模块时会优先搜索当前目录,因为当前目录内有以pandas命名的文件,所以import失败。

本地机安装完pycharm后无法打开,显示如图信息,网上未能找到真实可用的32-
bit JDK资源。


image.png

12-27

如何连接多个dataframe?

使用concat纵向合并,frm3=pd.concat([frm1,frm2],axis=0,ignore_index=True),#注意这里是concat,很容易记成contact;ignore_index=True可以对合并后的frm重新按顺序命名行标题。
使用append合并,只有纵向合并没有横向,frm3=frm1.append(frm2,ignore_index=True)

12-23

如何建立指定行列的随机数组?

np.random.randn(行数,列数)

如何建立以某一日期开始的连续日期?

pd.date_range('日期',periods=数量)

如何建立dataframe?

pd.DataFrame(已有数组,index=行标题list,columns=列标题list)

如何获取dataframe的行、列、数据信息?

df=某dataframe
行信息 df.index
列信息 df.columns
数据信息df.values

如何获取df指定位置的数据信息?

df.loc['行标题']
df.loc[:,['列标题']
df.loc['行标题','列标题']
df.iloc[[所在行数(从0开始)],:]或者 df.iloc[行范围,:]
df.iloc[:,[所在列数]]或者 df.iloc[:,列范围]
df.iloc[所在行数,所在列数]

如何筛选df中某指定列中指定值的数据

df[df[‘指定列’].isin([‘指定值’])]

12-8

如何恢复出list文件中的对象?

使用pickle
import pickle
打开list文件: f=open(文件所在位置包含文件名,读取方式rb代表读二进制)
恢复文件中对象(所有): pickle.load(f)

如何把frame转化成excel?

**.to_excel(文件所在地址包含文件名,sheet名)

如何把tushare接口数据提取到本地excel?

import pickle
import tushare as ts
f=open(r'D:\ww\trade_code.list','rb')
ts.set_token('12345)#这里写入token码
pro=ts.pro_api()
for i in pickle.load(f):
    if str(i).startswith('6'):
        ii=i+'.SH'
        df=pro.balancesheet(ts_code=ii,period='20180630',start_date='20180101',end_date='20180630')
        address=r'd:\ww\bs'+r'\\'+i+r'.xlsx'
        df.to_excel(address,sheet_name='bs')
    else:
        ii = i + '.SZ'
        df = pro.balancesheet(ts_code=ii, period='20180630', start_date='20180101', end_date='20180630')
        address = r'd:\ww\bs' + r'\\' + i + r'.xlsx'
        df.to_excel(address, sheet_name='bs')

11-29

安装python新模块的方法

1:files---settings---project---project interpreter---'+'----搜索-----install
2:windows键+r-----cmd-----pip install tushare

默写使用tushare接口调出资产负债表

import tushare as ts
ts.set_token('token码')
pro=ts.pro_api()
df=pro.balancesheet(ts_code='股票代码‘,period='报告期',start_date=’报告开始日',end_date='报告结束日‘)

得到结果

  ts_code  ann_date f_ann_date  end_date report_type comp_type  \
0  000651.SZ  20180831   20180831  20180630           1         1   

    total_share      cap_rese  undistr_porfit  surplus_rese    ...      \
0  6.015731e+09  1.038806e+08    6.854628e+10  3.499672e+09    ...       

  lt_payroll_payable  oth_comp_income  oth_eqt_tools  oth_eqt_tools_p_shr  \
0        112708961.0    -1.693679e+08           None                 None   

   lending_funds  acc_receivable  st_fin_payable  payables  hfs_assets  \
0           None            None            None      None        None   

   hfs_sales  
0       None  

[1 rows x 137 columns]

11-25

urlretrieve的使用方法?

urlretrieve(下载地址,保存地址,貌似与下载进度有关暂时不用)
注意点: 保存地址需写完整地址包括文件名,同时后缀需要有对应格式。

没办法了,把文件命名方法抄一遍,加深印象

downloadDirectory =r'd:\temp'
def getDownloadPath(baseUrl,fileUrl,downloadDirectory):
path = fileUrl.replace(baseUrl,'')
directory=ox.path.dirname(path)
if not os.path.exists(directory):
os.makedirs(directory)
return path

11-22

import requests
params={'form_email':'ss','form_password':'11'}
r=requests.post('https://www.douban.com/accounts/login',data=params)
print(r.text)

bs4中的find和findAll区别汇总

find找到匹配的第一个,findAll找到所有匹配;
find得到的是tag,findAll得到的是list,因此find(*****)后可以直接加'.子标签',.get_text(),['属性标签']

如何使用re.sub对指定字符串去头去尾?

re.sub(^ ,' ') re.sub( $,' '),且可以引用变量。

对request的结果.url .text .status_code区别?

.url显示url地址 .text显示更多信息(包括url) .status_code显示响应码

selenium下选择器如何使用?

单个 driver.find_element_by_(' ')
多个 driver.find_elements_by_
(' ')

如何使用隐式等待?

webDriver加expected_conditions 表示 等到某个标志出现时 开始摘取数据

如何找到requests post的有效地址?

输入发送信息后 在网页-检查-network中找到

想要连接字符串‘a’ 'b' ''怎么做?

'a'+'\'+'b' 因为\在字符串中可以与其他字母形成其他含义 所以需用'\'

11-21

findAll(*****)后面直接加.get_text()为何会报错?

.findAll得到的是list格式,所以无法直接加.get_text()

11-18

attrs global random datatime的作用?

.attrs['属性名称'],用来获取属性名称,与直接[属性名称]等同

收集整个网站数据

求注释

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
pages = set()
def getLinks(pageUrl):
  global pages
     html = urlopen("http://en.wikipedia.org"+pageUrl)
     bsObj = BeautifulSoup(html)
     try:
        print(bsObj.h1.get_text())
        print(bsObj.find(id="mw-content-text").findAll("p")[0])
        print(bsObj.find(id="ca-edit").find("span").find("a").attrs['href'])
      except AttributeError:
        print("页面缺少一些属性!不过不用担心!")
      for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")):
          if 'href' in link.attrs:
            if link.attrs['href'] not in pages:
              # 我们遇到了新页面
                newPage = link.attrs['href']
                print("----------------\n"+newPage)
                pages.add(newPage)
                getLinks(newPage)
getLinks("")

11-16

什么是正则表达式

用来查找符合某种条件的字符串的方法。

有哪些常用的符号(以下为默写)

. 匹配换行符以外所有字符

  • 重复0次或多次
    +重复1次或多次
    \b以单词开头或结束
    \d匹配数字 类似 [0-9]
    \w匹配数字汉子字母下划线
    \s匹配空格
    ^字符串开始
    $字符串结束
    \取消字符的特殊含义
    ?重复0次或1次
    {n}重复n次
    {n,}重复n次或更多次
    {n,m}重复n到m次
    [ ]匹配括号内任意一个
    |分支条件 注意 匹配分支条件时从左往右匹配 如果满足某个分支就不会管其他条件
    ()分组
    [^ ]匹配 除 外
    零宽断言(?=。。。)匹配以。。。结尾的字符的前面部分
    (?<=。。。)匹配以。。。开头的字符的后面部分
    (?!。。。)匹配不以。。。结尾的字符的前面部分
    (?<!。。。)匹配不以。。。开头的字符的后面部分
    *? 贪婪匹配 重复0或多次 尽可能少的重复

怎么获取某标签下的某属性?

findAll(' ... ',{'..':'...'})

为何使用get_text()?

把 html文档中的标签都清除,最后只包含字符串。

亲戚关系?

子(直接下一级) child 后代(所有下级)descendant
兄弟(同级)next_siblings 父(直接上级)parent

11-15之前

如何从网上爬信息?

大致思路
获取所在信息的网址--->>用html=urlopen(wangzhi)打开网址--->>用bsobj=BeautifulSoup(html,'lxml')把网站所有代码转化为bs对象(注意lxml是解析方式,目前比较推荐的)--->>通过“检查”网址的所有代码找到所需信息的所在位置---->>通过查找删选找到所需信息并归集(正则表达式、bs的find系列,其中的findall非常常用)

如何输出word文档内容?

将word文件转为二进制数据-->>对word文件进行解压得到存储内容的xml格式文件-->>再将xml文件转化为bs对象wordobj

wordFile = urlopen("http://pythonscraping.com/pages/AWordDocument.docx").read()
wordFile = BytesIO(wordFile)
document = ZipFile(wordFile)
xml_content = document.read('word/document.xml')

wordObj = BeautifulSoup(xml_content.decode('utf-8'), "lxml-xml")

1803.1已默写

from urllib.request import urlopen
from urllib.error import HTTPError
from bs4 import BeautifulSoup

def getTitle(url):
    try:
        html = urlopen(url)#打开网址转成response格式
    except HTTPError as e:#url错误时执行
        print(e)
        return None
    try:
        bsObj = BeautifulSoup(html, "lxml")#转成bs对象
        title = bsObj.body.h1#取出title
    except AttributeError as e:#发生错误时执行
        return None
    return title

title = getTitle("http://www.pythonscraping.com/exercises/exercise1.html")
if title == None:
    print("Title could not be found")
else:
    print(title)

1803.2已默写

附上找到的p标签
image.png
import re  #插入正则函数
import string
from urllib.request import urlopen
from bs4 import BeautifulSoup
url = 'https://book.douban.com/subject/24753651/discussion/58975313/'
html=urlopen(url)#打开url 转成response格式
bsobj=BeautifulSoup(html.read(),'xml')#转化成bs对象
comment=bsobj.findAll('p')#找到p标签内容
for emails in comment:
    emails=re.findall('([A-Za-z0-9\.\_]+\@(163|qq)\.com)',emails.get_text())#利用正则表达式找出邮箱,得到很多个list
    if emails !=[]:
        for email in emails:
            em =email[0]#查找出来的email是列表,用第一项
            em=em.strip(string.punctuation)#去掉收尾的标点符号
            print(em)

1803.03已注释

获取‘src’属性的截图

image.png
image.png
import os#插入os模块  处理文件和目录
import re#正则函数模块
from urllib.request import urlretrieve
from urllib.request import urlopen
from bs4 import BeautifulSoup

downloadDirectory = r'd:\temp'

def getDownloadPath(baseUrl, fileUrl, downloadDirectory):
    path = fileUrl.replace(baseUrl, '')#把“fileurl”中的‘baseurl’替换成空
    path = downloadDirectory+r'\\'+path
    directory = os.path.dirname(path)#获取path所在文件夹位置
    if not os.path.exists(directory):#如果文件夹不存在
        os.makedirs(directory)#新建一个文件夹
    return path

html = urlopen("https://book.douban.com/subject/24753651/discussion/58975313/")
bsObj = BeautifulSoup(html, "html.parser")
downloadList = bsObj.findAll('img')#获取img标签

for download in downloadList:
    fileUrl = download['src']
    baseUrl = os.path.dirname(fileUrl)#获取fileurl所在文件夹位置
    if fileUrl is not None:
        print(fileUrl)
        urlretrieve(fileUrl, getDownloadPath(baseUrl, fileUrl, downloadDirectory))##在fileurl地址下载并保存为path

1803.04已注释可默写

import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://exif.tuchong.com/view/5775300/'
html = urlopen(url)
bsObj = BeautifulSoup(html.read(), 'lxml')
tables = bsObj.findAll('table')#找到table标签

csvFile = open('exif.csv', 'wt', newline='',encoding='utf-8')#打开exif
writer = csv.writer(csvFile)#在csvfile中写入
try:
    for table in tables:
        headline = table.parent.find('h2').get_text()#找到H2标签
        writer.writerow('')
        writer.writerow([headline])#在writer中写入
        rows = table.findAll('tr')
        for row in rows:
            csvRow = []
            for cell1 in row.findAll('td',{'class':'exif-desc'}):
                csvRow.append(cell1.get_text())#在csvrow中添加信息
            for cell2 in row.findAll('td',{'class':'exif-content'}):
                csvRow.append(cell2.get_text())#在csvrow中添加信息
            writer.writerow(csvRow)#把csvrow写入writer
finally:
    csvFile.close()

1805已注释

import csv#插入写入文档模块
from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'http://baike.baidu.com/fenlei/%E6%A4%8D%E7%89%A9'
html = urlopen(url)
bsObj = BeautifulSoup(html.read(), 'lxml')
# tables = bsObj.findAll('table')

csvFile = open('baike_zhiwu.csv', 'wt', newline='',encoding='utf-8')
writer = csv.writer(csvFile)#在csvFile中写入
try:
    headlines = ['名称','简介','开放分类']
    writer.writerow(headlines)#写入headlines
    rows = bsObj.findAll('div', {'class': 'list'})#摘取div class list标签
    for row in rows :
        csvRow = []
        csvRow.append(row.find('a',{'class':'title nslog:7450'}).get_text())#在csv中加入信息
        csvRow.append(row.find('p').get_text())#在csv中加入信息
        # print(csvRow)
        for cell1 in row.findAll('div',{'class':'text'}):
            csvRow.append(cell1.get_text())#在csv中加入信息
        writer.writerow(csvRow)#把csvrow写入writer中
finally:
    csvFile.close()#关闭csv文件

1803.6已注释

from zipfile import ZipFile#解压缩模块
from urllib.request import urlopen
from io import BytesIO#二进制模块
from bs4 import BeautifulSoup

wordFile = urlopen("http://pythonscraping.com/pages/AWordDocument.docx").read()
wordFile = BytesIO(wordFile)#转化成二进制格式
document = ZipFile(wordFile)#解压缩
xml_content = document.read('word/document.xml')#读取document
wordObj = BeautifulSoup(xml_content.decode('utf-8'), "lxml-xml")#转成bs对象
textStrings = wordObj.findAll("w:t")#摘取'w:t'标签
for textElem in textStrings:
    closeTag = ""
    try:
        style = textElem.parent.previousSibling.find("w:pStyle")##从textelem的parent找到‘w:pstyle’标签
        if style is not None and style["w:val"] == "Title":
            print("<h1>")
            closeTag = "</h1>"
    except AttributeError: #不打印标签
        pass
    print(textElem.text)
    print(closeTag)

1803.8已注释

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re
import string


def cleaninput(input):
    input = re.sub('\\n+', '', input)#把换行符去掉(1或多个)
    input = re.sub(' +', '', input)#把空格去掉(1或多个)
    input = re.sub('\[[0-9]*\]', '', input)#把[]里的数字输掉(0或多个)
    input = bytes(input, 'utf-8')#转成二进制格式
    input = input.decode('ascii', 'ignore')#转成ascii格式
    cleaninput = []
    input = input.split(' ')#按空格分割
    for item in input:
        item = item.strip(string.punctuation)#两边去标点符号
        if len(item) > 1 or (item.lower() == 'a' or item.lower() == 'i'):#lower小写字母
            cleaninput.append(item)
    return cleaninput


def ngrams(input, n):
    input = input.split(' ')
    output = []
    for i in range(len(input) - n + 1):
        output.append(input[i: i + n])
    return output


html = urlopen("http://en.wikipedia.org/wiki/Python_(programming_language)")
bsObj = BeautifulSoup(html.read(), 'xml')
content = bsObj.find("div", {"id": "mw-content-text"}).get_text()
ngrams = ngrams(content, 2)
content = cleaninput(content)
print(ngrams)
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容

  • Python中的正则表达式(re) import rere.match #从开始位置开始匹配,如果开头没有则无re...
    BigJeffWang阅读 7,015评论 0 99
  • 一、快捷键 ctr+b 执行ctr+/ 单行注释ctr+c ...
    o_8319阅读 5,770评论 2 16
  • python的re模块--细说正则表达式 可能是东半球最详细最全面的re教程,翻译自官方文档,因为官方文档写的是真...
    立而人阅读 22,784评论 4 46
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 4,341评论 0 5
  • 一个人工作,一个人看书,一个人吃饭,一个人看电视,一个人睡觉。一个人感觉到寂寞难耐的时候,你一定会想找个人同住。但...
    陈二楠阅读 2,501评论 3 39