Pythonのrequestsでスクレイピングの勉強をはじめました。
お店の名前と、お店のURL、お店ページのdescriptionを取得してテキストに保存したいと考えています。
現状のコードはこちらです。
環境
Python 3.10
PyCharm 2021.3.1
Windows 10
Python
1import requests 2from bs4 import BeautifulSoup 3 4user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) " \ 5 "Chrome/98.0.4758.80 Safari/537.36 " 6header = {'User-Agent': user_agent} 7 8url = 'https://' 9res = requests.get(url, headers=header) 10soup = BeautifulSoup(res.text, 'html.parser') 11 12shop_names = soup.find_all(class_='tit-shoplist') 13 14for shop_name in shop_names: 15 # print(shop_name.text)# 店名取得 16 # print(shop_name.a.attrs['href'])# URL取得 17 shoptxt1 = shop_name.text.replace('\n', '') 18 shoptxt2 = shop_name.a.attrs['href'] + "\n" 19 # リスト型に整形 20 shoptxt3 = [shoptxt1 + ",\n" + shoptxt2] 21 22 # urlのリスト化 23 url_list = [shop_name.a.attrs['href']] 24 # urlをstr化 requestsで読み込ませるために 25 strurl = ','.join(url_list) 26 27 # ショップのURLへアクセス 28 descres = requests.get(strurl, headers=header) 29 # ショップURLのパース 30 descrip = BeautifulSoup(descres.text, 'html.parser') 31 shop_desc = descrip.find_all('meta', {'name': 'description'}) 32 # time.sleep(1) 33 34 # テキストに保存 35 with open('./omiseichiran.txt', 'a+', encoding='utf-8') as fw: 36 for a in shoptxt3: 37 fw.write(a) 38 for c in shop_desc: 39 fw.write("%s\n" % c + '\n\n') 40 print(shoptxt3, shop_desc)
お店の名前とURLは取得できるようになりましたが、
30店舗ほどあるお店ページへ飛ぶときに、接続エラー(運営がされていないドメイン)に出くわすようになりました。
TimeoutError: [WinError 10060] 接続済みの呼び出し先が一定の時間を過ぎても正しく応答しなかったため、接続できませんでした。または接続済みのホストが応答しなかったため、確立された接続は失敗しました。
その際、接続タイムアウトエラーが出ると、処理が止まってしまうため、
接続できないドメインがある場合はスキップし、処理を継続させたいと考え、
try exceptやif notの例外処理を試しましたが、requestsのエラーで止まってしまいます。
Python
1 with open('./omiseichiran.txt', 'a+', encoding='utf-8') as fw: 2 for a in shoptxt3: 3 fw.write(a) 4 for c in shop_desc: 5 if descres.status_code != 200: 6 fw.write("%s\n" % c + '\n\n') 7 if not descres.status_code != 200: 8 continue 9 print(shoptxt3, shop_desc)
エラーが出た場合でもループを継続したい場合はどのような対応をするといいのでしょうか。
何卒よろしくお願いいたします。
追記
教えていただいたrequestsの処理をしてもエラーが出たら止まってしまいます。
Python
1 for a in shoptxt3: 2 print(shoptxt3, shop_desc) 3 try: 4 for c in shop_desc: 5 print(descres.status_code) 6 except (requests.exceptions.ConnectionError, TimeoutError): 7 print("error") 8

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/02/15 14:19