ウェブ・スクレイピング2020年7月31日 | |
はじめにPython を使ってウェブから情報を取る。 環境
ウェブから情報を取得する情報の取得に requests、情報の抽出に BeautifulSoup を用いる。 import requests from bs4 import BeautifulSoup url = "http://penguinitis.g1.xrea.com" response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") for item in soup.find_all("a"): print(item) ここではアンカーのみ表示している。 とりあえず取るprint(soup.prettify()) とりあえず取ってみて、データを観察して方針を決める。 リンクを取るたとえば、td 要素の "link" クラスの中にアンカーがあって、それから href の値を取り出したい場合は、以下のようになる。 href = [] for item in soup.find_all("td", class_="link"): anchor = item.select("a") if anchor != []: href.append(anchor[0].attrs["href"]) PDF の取得response = requests.get(url) with open("file.pdf", "wb") as f: f.write(response.content) 更新日時の取得response = requests.head(url) s = response.headers["Last-Modified"] Windows 認証Windows 認証 (NTLM 認証) が必要なサイトに接続するには、requests_ntlm を用いる。 $ pip install requests_ntlm import requests from bs4 import BeautifulSoup from requests_ntlm import HttpNtlmAuth url = "http://xxxx" username = "xxxx" password = "xxxx" response = requests.get(url, auth=HttpNtlmAuth(username, password)) soup = BeautifulSoup(response.text, "html.parser") ... | |
PENGUINITIS |