[Python 爬虫这样学,一定是大拇指拉!] DAY23 - 实战演练:HTML Response - 抓取股票代码清单 (2)

开始前我简单带过一下我们这支爬虫 Beautiful soup 的用法好了:

from bs4 import BeautifulSoup
html = "<title>example1</title><title>example2</title>"

soup = BeautifulSoup(html, "lxml")

# find_all() 会搜寻整个 html 回传符合的值
print(soup.find_all("title"))
# [<title>example1</title>, <title>example2</title>]

# find() 只会回传"第一个"符合的值
print(soup.find("title"))
# <title>example1</title>

# 拿取 tag 之间的 text
print(soup.find("title").text)
# example1

官方文件传送门

大概是这样,其实没有很难对吧!/images/emoticon/emoticon12.gif

那麽,要开始罗!

抓取股票代码清单 - 程序

  • 根据前篇得到的资讯:

    • URL:https://isin.twse.com.tw/isin/class_main.jsp
    • 必要的 Query:market=1&issuetype=1&Page=1&chklike=Y
    • 所以可以根据需求在 Query 的 market、issuetype、Page、chklike 代入自己要的值。
    • HTTP Method 是 GET。
    • Content-Type:text/html;charset=MS950,所以格式是 HTML,编码为 MS950。
  • 爬虫程序:

    Beautiful soup 看不懂的地方,请开启上方提供的官方文件传送门搭配使用。

    import json
    import requests
    from bs4 import BeautifulSoup
    
    # 设置 index constant,数字代表我们要的资料在 list 的位置
    TARGET_TABLE_INDEX = 1
    STOCK_NO_INDEX = 2
    STOCK_NAME_INDEX = 3
    STOCK_INDUSTRY_INDEX = 6
    # JSON settings
    TITLE = "stock"
    JSON_INDENT = 4
    
    # 送出 HTTP Request
    url = "https://isin.twse.com.tw/isin/class_main.jsp"
    res = requests.get(url, params={
        "market": "1",
        "issuetype": "1",
        "Page": "1",
        "chklike": "Y"
    })
    
    # 处理编码,使用预设 utf-8 的话 res.text 的内容会有乱码
    res.encoding = "MS950"
    res_html = res.text
    
    # Parse
    soup = BeautifulSoup(res_html, "lxml")
    
    # 因为这个 HTML 里面有两张 table
    # 所以我们 find_all("table") 回传的 list 的 length 会是 2
    # 而我们要的资料在第二张
    tr_list = soup.find_all("table")[TARGET_TABLE_INDEX].find_all("tr")
    
    # tr_list 的第一个是 item 是栏位名称
    # 我们这边用不到所以 pop 掉
    tr_list.pop(0)
    
    # 开始处理资料
    result = []
    for tr in tr_list:
    
        td_list = tr.find_all("td")
    
        # 股票代码
        stock_no_val = td_list[STOCK_NO_INDEX].text
    
        # 股票名称
        stock_name_val = td_list[STOCK_NAME_INDEX].text
    
        # 股票产业类别
        stock_industry_val = td_list[STOCK_INDUSTRY_INDEX].text
    
        # 整理成 dict 存起来
        result.append({
            "stockNo": stock_no_val,
            "stockName": stock_name_val,
            "stockIndustry": stock_industry_val
        })
    
    
    # 将 dict 输出成档案
    stock_list_dict = {TITLE: result}
    with open("stock_info_list.json", "w", encoding="utf-8") as f:
        f.write(
            json.dumps(stock_list_dict,
                       indent=JSON_INDENT,
                       ensure_ascii=False)
        )
    

    档案就会长这样:
    https://ithelp.ithome.com.tw/upload/images/20211008/20139358f7xEuLPVFj.png

以上就是抓取股票清单的方法!


<<:  Day 25 : Tkinter实战,配合pillow制作简易的处理照片程序(上)

>>:  D28 - 用 Swift 和公开资讯,打造投资理财的 Apps { 三大法人成交比重实作.3 }

自己做个好用的pysdie 2 cheat sheet

在很多地方都流行可以随时查找的cheatsheet,那PySide2 有吗? 笔者不清楚,乾脆直接做...

今日爬山中

初版待更新(还是翻新),9月19日中秋节前夕,爬山旅行中。 网路收讯极差,慌张的寻找网路与讯号点。 ...

LeetCode解题 Day17

350. Intersection of Two Arrays II https://leetcod...

DAY 15 『 Realm 新增、修改、删除 』Part3

昨天分享如何新增、修改、删除、印出 Realm 资料库的资料,以及读取 Realm 资料库的资料去更...

Day 25 constructors、this、static

constructors : Java 中建立物件需要建构子,如果类别没有定义建构子,编译器就会提供...