LoginSignup
2
5

More than 3 years have passed since last update.

【Python】初心者でスクレイピングする時に冒頭脳死して書けるコード

Posted at

スクレイピングをするときに毎回毎回

test.py
from bs4 import BeautifulSoup

とこのように記述するのが面倒くさいので、とりあえずこれ使っとけば間違いなしのテンプレートを作成します。

test.py
!apt-get update
!apt install chromium-chromedriver
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
!pip install selenium
!pip install requests-html

まずはライブラリ関係。
私は普段clbを使っているので、とりあえずこれ入れとく。

test.py
import pandas as pd
import datetime
from tqdm.notebook import tqdm
import requests
from bs4 import BeautifulSoup
import time
import re
from urllib.request import urlopen
import urllib.request, urllib.error
from requests_html import HTMLSession
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# htmlを取得するところまで
options = webdriver.ChromeOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome('chromedriver',options=options)
driver.implicitly_wait(10)
url="https://www.XXX.com"
driver.get(url)
html = driver.page_source.encode('utf-8')
soup = BeautifulSoup(html, "html.parser")

はい、ここまで脳死でコピペでOKです。
あとは

test.py
soup

これで、とりあえずhtmlを出力するところまではものの数秒で到達できます。

厳密に言えば、tqdmとか使ってないライブラリもあるんですけど、個人的にスクレイピングするときにほぼ毎回セットで使用しているライブラリをインポートするコードも全部詰め込んでます。

私自身、これでコピペして使いまくってます。

2
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
5