1

Python3でselenium/BeautifulSoupを使って特定のWEBページでスクレイピング後、リスト文字データを抽出しました。
その後抽出したリストをメールで送信しています。
ただ下記のようにmessageでプリントされるリストのすべてメールに送信されないです。
何の原因か分かりますでしょうか。

ご指導をお願いできますでしょうか。

取得リスト
message

電話番号:0701232511
IMEI:812341050123456
ICCID:81234560074626223089
5G SINR:19.5 dB
5G RSRP:-102 dBm
ネットワーク名 (2.4GHz帯):TEST_L10_123ECF
ネットワーク名(5GHz帯):TEST_L12_234ECF_5G
最大アクセス数(5GHz帯メインSSID):30
最大接続数:40
Wi-Fiカバレッジ:長距離モード
IPアドレス:192.111.1.1
WAN側のIPアドレス:11.211.13.121
WAN側のIPv6アドレス:2111:0123:c123:1230:f4fc:12e3:1231:1b12
ソフトウェアバージョン:1.0.5_U

メールに送信されるリスト
message

ソフトウェアバージョン:1.0.5_U

Code

from selenium.webdriver.common.keys import Keys
import time
from selenium.webdriver.chrome.options import Options
from datetime import datetime as dt, date, timedelta
import pyautogui
import pyperclip
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
import urllib3
from torch import nn
from urllib3.exceptions import InsecureRequestWarning 
urllib3.disable_warnings(InsecureRequestWarning)
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
from email.mime.text import MIMEText
from email import encoders, message
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
import smtplib
from email.utils import formatdate

#headless background 
option = Options()
option.add_argument('--headless')

#Getting Default Adapter failed error message
option.add_experimental_option('excludeSwitches', ['enable-logging'])

strDate = dt.now().strftime("%Y%m%d")

today = dt.today()
(dt.strftime(today, '%Y-%m-%d'))

yesterday = today - timedelta(days=28)
(dt.strftime(yesterday, '%Y-%m-%d'))

URL= "http://192.111.1.1/index.html#test"

# ブラウザを開く。 #options=option background 
driver = webdriver.Chrome(executable_path="C:\\Users\\sun\\Documents\\python\\chromedriver.exe",options=option)

# Googleの検索TOP画面を開く。
driver.get(URL)
# 3秒待機
time.sleep(3)

# パスワードを入力
password = driver.find_element_by_name("txtPwd")
password.send_keys("1234")

#ログインボタンをクリック
login = driver.find_element_by_xpath('//*[@id="btnLogin"]')
login.click()

time.sleep(3)
#showDetailInfoボタンをクリック
showDetailInfo = driver.find_element_by_xpath('//*[@id="showDetailInfo"]')
showDetailInfo.click()


time.sleep(3)
# 検索先のページのHTMLを取得

html = driver.page_source.encode('utf-8')

soup = BeautifulSoup(html, 'lxml')
elems = [tag.text for tag in soup]
print(elems)


#詳細情報端末情報からソフトウェアバージョンのリストのみ取得
import re
lst = re.split(r'\n+', elems[0])
lst = lst[lst.index('詳細情報端末情報')+1:]
lst = lst[:lst.index('ソフトウェアバージョン')+2]

attr = dict()
for key, val in zip(*[iter(lst)]*2):
  attr[key] = val
  #リスト取得確認
  #print(attr)

#各項目のリストの間に:を追加
for k, v in attr.items():
   #news = attr.replace("電話番号","")
   message= k + ':' + v
   print(message)

#メール送信
sendAddress = 'example@'
password = '124'
subject = "【端末情報】"
bodyText = message
fromAddress =  'example@'
toAddress = 'example@'

# SMTPサーバに接続
smtpobj = smtplib.SMTP('smtp.gmail.com', 587)
smtpobj.starttls()
smtpobj.login(sendAddress, password)

# メール作成
msg = MIMEText(bodyText)
msg['Subject'] = subject
msg['From'] = fromAddress
msg['To'] = toAddress
msg['Date'] = formatdate()

# 作成したメールを送信
smtpobj.send_message(msg)
smtpobj.close()
            
4
  • うーん、message= k + ':' + v としているので、最後の項目しか message に残りませんね。
    – metropolis
    2021年9月8日 5:19
  • 回答ありがとうございます。すいません、よく分からないですが、printするとmessage には全てリストが表示されます。
    – 幸589
    2021年9月8日 7:50
  • message = '\n'.join(k + ':' + v for k, v in attr.items()) としてみるとよろしいかと思います。
    – metropolis
    2021年9月8日 7:53
  • ありがとうございます。Pythonで文字列を連結するさいに.joinを使いますね。またforの中に入れないといけないこと理解できました。丁寧に教えてくれてありがとうございます。
    – 幸589
    2021年9月8日 8:11

1 件の回答 1

1

下記の方法で解決できました。
①joinを追加して文字の連結を行う

例:code

list = ['My', 'name', 'is', '山田', '太朗']
str = ' '.join(list)
print(str)

実行結果

My name is 山田 太朗

②改行したいので '\n' を追加

③forを追加し、各アイテムの文字を連結を行う

修正した箇所

message = '\n'.join(k + ':' + v for k, v in attr.items())

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。