Skip to content

Instantly share code, notes, and snippets.

@shiumachi
Last active January 4, 2017 01:17
Show Gist options
  • Save shiumachi/b803012f7273c007d0750307f233ccde to your computer and use it in GitHub Desktop.
Save shiumachi/b803012f7273c007d0750307f233ccde to your computer and use it in GitHub Desktop.
PythonでのWebクローラ作成時に学んだことメモ

例外

try:
except (ConnectionError, ChunkedEncodingError, TooManyRedirects, NewConnectionError) as e:
                logging.warn("Skip URL {} Reason: {}".format(url, e))

SQLite

構文

replace

SQLiteでは upsert をするときは replace を使う。

sqlite3 コマンド

$ sqlite3 foo.db

.schema TABLE

テーブルのスキーマを見る。未指定の場合全スキーマ。

Python における SQLite

sqlite3 モジュールを使う。

import sqlite3

conn = sqlite3.connect(db_path)
c = conn.cursor()
# ...処理...
# コミットが必要なら conn.commit()
conn.close()

cursor.execute(sql_statement)

SQL文一行実行。複数行は executescript() を使う。

引数として変数を渡す

    cursor.execute('replace into tbl_a(url, title) values (?,?)', (url, title))

タプルで渡すことに注意。

実行結果はタプルで返ってくる

結果が1行でも当然タプルなので、中の値だけ使う場合は一度取り出す必要がある。

SQLファイルを読み込む

ファイルのまま渡すことができないので一度読み出して executescript() で渡す。

    f = open(sql_file)
    script = f.read()
    f.close()

    c.executescript(script)
    conn.commit()

ロギング

logging モジュールを使う。

import logging

logging.getLogger().setLevel(logging.DEBUG)

ログを書き込みたい場合は以下のように書く。

logging.info("adding URL to DB: {}".format(url))

requests と BeautifulSoup によるWebスクレイピング

import requests
from bs4 import BeautifulSoup

r = requests.get(url)
soup = BeautifulSoup(r.content, "lxml")
for td in soup.find_all("td", attrs={"class": "someClassInThePage"}):
    href = td.find("a")
    title = href.text

必要なタグの探し方

Chromeの検証で楽に探せる。

pylint と autopep8

pylint でエラーのみ出力する

$ pylint -E foo.py

autopep8

$ autopep8 foo.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment