LoginSignup
31
43

More than 5 years have passed since last update.

PythonのWebスクレイピングでproxy経由でのhttpsアクセスがrequestsを使ったら簡単だった

Posted at

Python3でurllibとBeautifulsoupでWebスクレイピングに挑戦しています。
前回はProxyがあるため、通信エラーが起こることに対処しました。
  PythonのWebスクレイピングでProxy設定のため応答がなかったときの対処
httpによる通信は上記の方法でうまくいったが、httpsのサイトになったときに通信が確立されずにエラーとなってしまいました。
最近のWebサイトはhttpsが多いので困りました。。:disappointed_relieved:
前回の方法で下記のようにproxiesに"https"の項目を追記しても解決しません。
proxies={"http":"http:proxy.-----.co.jp/proxy.pac",
"https":"http:proxy.-----.co.jp/proxy.pac"}

調べていると、requestsというライブラリがありました。urllibの代わりに使えるか試してみたら、驚くほど簡単に解決しました。

使い方例は以下です。

requsts_sample.py
import requests

proxies = {
"http":"http://proxy.-----.co.jp/proxy.pac",
"https":"http://proxy.-----.co.jp/proxy.pac"
}
r = requests.get('https://github.com/timeline.json', proxies=proxies)
print(r.text)

Beautifulsourpを使う場合は、requests.getで取得したオブジェクトのcontentを渡せばよいようです。
簡単なサンプルを示します。

import requests
from bs4 import BeautifulSoup

proxies = {
'http':'http://proxy.-----.co.jp/proxy.pac',
'https':'http://proxy.-----.co.jp/proxy.pac'
}

def getBS(url):
    html = requests.get(url, proxies=proxies)
    bsObj = BeautifulSoup(html.content, "html.parser")
    return bsObj

htmlSource = getBS("https://en.wikipedia.org/wiki/Kevin_Bacon")

# ページに存在するリンク先を表示する
for link in htmlSource.findAll("a"):
    if 'href' in link.attrs:
        print(link.attrs['href'])

requestsライブラリはAnacondaでPython 3.5.2をインストールしたときに、入っていました。
Anaconda Navigatorでインストールしたパッケージが確認できます。WindowsでGUIインストールした場合は、Windows->すべてのプログラム->Anaconda3->Anaconda Navigatorにあります。

requestsライブラリのQuickstartはこちら

31
43
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
31
43