1

解析結果をテキスト ファイルに保存する必要があります。

import urllib
from bs4 import BeautifulSoup
import urlparse

path = 'A html file saved on desktop'

f = open(path,"r")
if f.mode == 'r':       
    contents = f.read()

soup = BeautifulSoup(contents)
search = soup.findAll('div',attrs={'class':'mf_oH mf_nobr mf_pRel'})
searchtext = str(search)
soup1 = BeautifulSoup(searchtext)   

urls = []
for tag in soup1.findAll('a', href = True):
    raw_url = tag['href'][:-7]
    url = urlparse.urlparse(raw_url)
    urls.append(url)
    print url.path

with open("1.txt", "w+") as outfile:
    for item in urls:
        outfile.write(item + "\n")

しかし、私はこれを取得します: Traceback (most recent call last): File "c.py", line 26, in outfile.write(item + "\n") TypeError: can only concatenate tuple (not "str") to tuple .

タプルを文字列に変換してテキスト ファイルに保存するにはどうすればよいですか? ありがとう。

4

1 に答える 1

1

問題は、item呼び出されたリストのそれぞれurlstuple. タプルは他のアイテムのコンテナであり、不変でもあります。を実行するとitem + "\n"、インタプリタにタプルと文字列を連結するように要求することになりますが、これは不可能です。

代わりに、タプルを検査し、各項目のフィールドの 1 つを選択して出力ファイルに書き込みます。

with open("1.txt", "w+") as outfile:
    for item in urls:
        outfile.write(str(item[1]) + "\n") 

ここでは、タプル項目の最初のフィールドが最初に文字列に変換され (それが何か他のものである場合)、次に "\n" で連結されます。タプルをそのまま書きたい場合は、次のように書きます。

outfile.write(str(item) + "\n")
于 2014-11-18T18:00:40.077 に答える