1

\nそれで、CLから取得したWebページをフォーマットして、メールに送信できるようにしようとしましたが、これは、とを削除するために何かを試みるたびに思いつくものです\t

b'\n\n\n\t\n\t\n\t\n\t\n\t\n\t\n\n\n\n\t\n\n\n\t
\n\t\t\t
\n\t
\n\t\t
\n\t\t\t
\n 0 favorites\n
\n\n\t\t
\n\t\t
∨
\n\t\t
∧
\n\t\t
\n \n
\n
\n\t \tCL wenatchee all personals casual encounters\n
\n
\n\t\t
\n\t
\n
\n\n\t\t
\n\t\t\t
\n\t\n\t\t\n\t\n\n\n\nReply to: 59nv6-4031116628@pers.craigslist.org\n
\n\n\n\t
\n\t\n\t\tflag [?] :\n\t\t\n\t\t\tmiscategorized\n\t\t\n\t\t\tprohibited\n\t\t\n\t\t\tspam\n\t\t\n\t\t\tbest of\n\t\n
\n\n\t\t

Posted: 2013-08-28, 8:23AM PDT
\n
\n\n
\n \n Well... - w4m - 22 (Wenatchee)\n

私はストリップ、置換、さらには正規表現を試しましたが、何も気になりません。すべての影響を受けずに、常にメールに表示されます。

コードは次のとおりです。

try:
    if url.find('http://') == -1:
        url = 'http://wenatchee.craigslist.org' + url
    html = urlopen(url).read()
    html = str(html)
    html = re.sub('\s+',' ', html)
    print(html)
    part2 = MIMEText(html, 'html')
    msg.attach(part2)
    s = smtplib.SMTP('localhost')
    s.sendmail(me, you, msg.as_string())
    s.quit()
4

1 に答える 1

6

あなたの問題は、反対のすべての証拠にもかかわらず、あなたが望んでいるbytesものではなく、まだオブジェクトを持っているということです。strしたがって、エンコーディングが指定されていないと、何か (正規表現、置換パラメーターなど) を文字列に一致させる方法がないため、試みは何も起こりませんhtml

あなたがする必要があるのは、最初にバイトをデコードすることです。

個人的には、空白をクリーンアップするための私のお気に入りの方法は、string.splitandを使用することstring.joinです。これが実際の例です。あらゆる種類の空白のすべての実行を削除し、それらを単一のスペースに置き換えます。

try:
    html = urlopen('http://wenatchee.craigslist.org').read()
    html = html.decode("utf-8") # Decode the bytes into a useful string
    # Now split the string over all whitespace, then join it together again.
    html = ' '.join(html.split())
    print(html)
    s.quit()
except Exception as e:
    print(e)
于 2013-08-28T23:34:11.813 に答える