愛媛県のインフルエンザ患者報告数をスクレイピング

colspanがめんどくさいので直取り

import requests
from bs4 import BeautifulSoup

headers = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'
}


def get_table(url):

    r = requests.get(url, headers=headers)

    if r.status_code == requests.codes.ok:

        soup = BeautifulSoup(r.content, 'html5lib')

        tables = soup.find_all('table', class_='datatable')

        return tables


def scraping(tables, num, area):

    # 今週
    this_week = float(tables[4].select_one(
        'tr:nth-of-type(3) > td:nth-of-type({})'.format(num + 1)).get_text(
            strip=True))

    # 前週
    last_week = float(tables[4].select_one(
        'tr:nth-of-type(5) > td:nth-of-type({})'.format(num)).get_text(
            strip=True))

    # 警報・注意報
    alarm = tables[4].select_one(
        'tr:nth-of-type(4) > td:nth-of-type({})'.format(num - 1)).get_text(
            strip=True)

    # 前週差
    comp_week = this_week - last_week

    if comp_week > 0:

        sign = '↑'
    elif comp_week < 0:
        sign = '↓'
    else:
        sign = ''

    # インフルエンザ患者報告数

    this_count = tables[0].select_one(
        'tr:nth-of-type(2) > td:nth-of-type({})'.format(num)).get_text(
            strip=True)

    # 迅速検査結果

    temp = []

    inful_a = tables[0].select_one(
        'tr:nth-of-type(4) > td:nth-of-type({})'.format(num + 1)).get_text(
            strip=True)
    inful_b = tables[0].select_one(
        'tr:nth-of-type(5) > td:nth-of-type({})'.format(num)).get_text(
            strip=True)
    inful_n = tables[0].select_one(
        'tr:nth-of-type(6) > td:nth-of-type({})'.format(num)).get_text(
            strip=True)

    if inful_a:
        temp.append('A型:{}人'.format(inful_a))

    if inful_b:
        temp.append('B型:{}人'.format(inful_b))

    if inful_n:
        temp.append('不明:{}人'.format(inful_n))

    inful_kata = '、'.join(temp)

    result = '({0}){1}\n定点当たり:{2:.1f}人{3}(前週比:{4:+.1f}人)\n患者報告数:{5}人({6})'.format(
        area, alarm, this_week, sign, comp_week, this_count, inful_kata)

    return result


# 02:愛媛県
# 03:四国中央
# 04:西条
# 05:今治
# 06:松山市
# 07:中予
# 08:八幡浜
# 09:宇和島

if __name__ == '__main__':

    tables = get_table(
        'https://www.pref.ehime.jp/h25115/kanjyo/topics/influ1819/tb_flu1819.html'
    )

    tables.extend(
        get_table(
            'https://www.pref.ehime.jp/h25115/kanjyo/topics/influ1819/index1819.html'
        ))

    # print(len(tables))

    if len(tables) == 5:

        temp = []

        temp.append('インフルエンザ患者報告数')

        temp.append(scraping(tables, 2, '愛媛県'))

        temp.append(scraping(tables, 5, '今治'))

        temp.append('https://www.pref.ehime.jp/h25115/kanjyo/index.html')

        result = '\n\n'.join(temp)

        print(result)
続きを読む

今治市の歯科医院を探す

import csv
import time
from urllib.parse import parse_qs, urljoin, urlparse

import requests
from bs4 import BeautifulSoup

headers = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'
}


def scraping(url):

    r = requests.get(url, headers=headers)

    if r.status_code == requests.codes.ok:

        soup = BeautifulSoup(r.content, 'html5lib')

        result = [
            td.get_text(strip=True)
            for td in soup.select('table#hor-zebra > tbody > tr > td')
        ]

        # GooglemapからURL取得
        gmap = soup.select_one(
            'table#jyouhou-table > tbody > tr > td > div > iframe').get('src')

        # URLからquery取得
        temp = parse_qs(urlparse(gmap).query)

        # queryから緯度・経度取得
        lon, lat = temp['q'][0].replace('loc:', '').split(',')

        return ([lon, lat] + result)


if __name__ == '__main__':

    # 愛媛県歯科医師会より今治市の歯科医院を探す
    url = 'https://www.ehimeda.or.jp/doctor/sdental_u/resultlist.php?selADD1=02&SelCount=5'

    r = requests.get(url, headers=headers)

    if r.status_code == requests.codes.ok:

        soup = BeautifulSoup(r.content, 'html5lib')

        with open('result.csv', 'w') as fw:
            writer = csv.writer(fw, dialect='excel', lineterminator='\n')

            # ヘッダーをスキップするため1からスタート
            for trs in soup.select('table#list-table > tbody > tr')[1:]:

                result = [td.get_text(strip=True) for td in trs.select('td')]

                link = urljoin(url, trs.select_one('a').get('href'))

                temp = scraping(link)

                writer.writerow(result + temp)

                time.sleep(1)

スクレイピング対策

ヘッドレスChromeJavaScriptを有効にする teratail.com

スクレイピング https://gather-tech.info/news/2017/08/14/Gather59.html

ヘッドレスChromeからのアクセスを検出する方法について。User Agentによる判定、プラグインの有無による判定、画像読み込みがエラーになるときのサイズによる判定方法などが紹介されている。

一般的なUser Agentによる判定だと簡単に偽装できてしまうのでそれ以外の検出方法が書かれていて参考になります。画像が読み込めない場合のサイズの違いで検出できるとは驚きです。

Detecting Chrome Headless https://antoinevastel.com/bot%20detection/2017/08/05/detect-chrome-headless.html

qiita.com

こちらの再現性を低くするぐらいだったらまだ大丈夫かな

「日経」の文字のタグを検索してその子を抽出でいける。 数字以外は消せばいいので「\D」で置換

from bs4 import BeautifulSoup
import re


def nikkei_find(tag):
    return ('日経' in tag.contents[0])


doc = """<div>日経平均株価<b>114514</b></div>
<div>日経平均株価<span>114514</span></div>
<div>日経平均株価<div id="yaju">114514</div></div>"""

soup = BeautifulSoup(doc, 'html.parser')

for i in soup.find_all(nikkei_find):
    text = re.sub(r'\D', '', i.contents[1].get_text(strip=True))
    print(text)

doc = """<div>日経平均株価<b>114514</b></div>
<div>日経平均株価<b>114,514</b></div>
<div>日経平均株価<b>114 514</b></div>"""

soup = BeautifulSoup(doc, 'html.parser')

for i in soup.find_all(nikkei_find):
    text = re.sub(r'\D', '', i.contents[1].get_text(strip=True))
    print(text)

Chromebook C223Nのアプリ関連

海外版のレッドから日本版になってやっと帰ってきた

症状は電源不良みたい、最初起動したまま一度も電源落ちなかったし

imabari.hateblo.jp

imabari.hateblo.jp

Androidアプリ

Video & TV SideView

  • 初期設定画面の分割画面を解除はchromebookを最新版にして最大化にするとOK
  • 再生中のメニューが消せないのでかなりみずらい。消し方がわからない。
  • デュアルディスプレイにしてたら再生されない。

Amazonプライム・ビデオ

  • コマ送りやすぐ止まり動かない
  • アンインストール、chromeで再生

TVer

  • 動かない
  • アンインストール、chromeで再生

動画関連はChromeで動かすのが間違いないのかも

デュアルディスプレイにしながらTVerを見ながらブラウザ開いて作業していたら後半フリーズ コマ送りになりながらもアプリ全部終了同時作業はきびしいかも

Ubuntu Serverにfirefox headless

Headless

wget https://github.com/mozilla/geckodriver/releases/download/v0.23.0/geckodriver-v0.23.0-linux64.tar.gz
tar -zxvf geckodriver-v0.23.0-linux64.tar.gz 

sudo chmod +x geckodriver
sudo mv geckodriver /usr/local/bin

sudo apt install firefox
sudo apt install python3-pip
pip3 install selenium --user
sudo apt install xvfb
/usr/bin/Xvfb :99 -ac -screen 0 1024x768x8 & export DISPLAY=":99"
# sudo apt install libpangocairo-1.0-0 libx11-xcb1 libxcomposite1 libxcursor1 libxdamage1 libxi6 libxtst6 libnss3 libcups2 libxss1 libxrandr2 libgconf2-4 libasound2 libatk1.0-0 libgtk-3-0
from selenium import webdriver
#from selenium.webdriver.firefox.options import Options

#options = Options()
#options.headless = True
#driver = webdriver.Firefox(options=options)

driver = webdriver.Firefox()

driver.get('http://www.yahoo.co.jp')

# ブラウザ操作
driver.save_screenshot("ss.png")

driver.quit()