2016-04-27 26 views
0

をBeautifulSoupない:PythonのBeautifulsoup:file.write(STR)メソッドを取得TypeError例外:書き込み()の引数はstrをしなければならない、私はコードの下に書いた

from bs4 import BeautifulSoup 
import sys # where is the sys module in the source code folder ? 

try: 
    import urllib.request as urllib2 
except ImportError: 
    import urllib2 


print (sys.argv) # 
print(type(sys.argv)) # 

#baseUrl = "https://ecurep.mainz.de.xxx.com/ae5/" 
baseUrl = "http://www.bing.com" 
baseUrl = "http://www.sohu.com/" 
print(baseUrl) 

url = baseUrl 
page = urllib2.urlopen(url) #urlopen is a function, function is also an object 
soup = BeautifulSoup(page.read(), "html.parser") #NameError: name 'BeautifulSoup' is not defined 

html_file = open("Output.html", "w") 
soup_string = str(soup) 
print(type(soup_string)) 
html_file.write(soup_string) # TypeError: write() argument must be str, not BeautifulSoup 
html_file.close() 

は、エラーの下に与えたコンパイラ:(しかしsoup_stringは明らかですコンパイラによって与えられたSTR、なぜ最初のエラー秒1が表示される理由 も知らない)

C:\hzg>py Py_logDownload2.py 1 
['Py_logDownload2.py', '1'] 
<class 'list'> 
http://www.sohu.com/ 
<class 'str'> 
Traceback (most recent call last): 
    File "Py_logDownload2.py", line 25, in <module> 
    html_file.write(soup_string) # TypeError: write() argument must be str, not 
BeautifulSoup 
    File "C:\Users\ADMIN\AppData\Local\Programs\Python\Python35\lib\encodings\ 
cp1252.py", line 19, in encode 
    return codecs.charmap_encode(input,self.errors,encoding_table)[0] 
UnicodeEncodeError: 'charmap' codec can't encode characters in position 376-377: 
character maps to <undefined> 

私は、コードを変更した場合、より多くの混乱が何であるか:?。

baseUrl = "https://ecurep.mainz.de.xxx.com/ae5/" 
#baseUrl = "http://www.bing.com" 
#baseUrl = "http://www.sohu.com/" 

コンパイルしてもエラーは発生しません。 (私は元の名前を "xxx"に変更しました)。

誰でもこれをデバッグできますか?

-----更新:

私は、Javaコードを記述するために使用され、Python用初心者です。あなたの助けを借りて、私はPythonのデバッグを進めてきたと思います。Javaをデバッグするときは、常に最初のエラーを解決しようとします。 Pythonでは最後に解決しようとします。右?

+0

によってコーディングエラー(推奨されません)を無視することができutf-8

import codecs f = codecs.open("test", "w", "utf-8") 

を使用してファイルを開こう取得する。 –

+0

@MartijnPietersによると、読み込みしようとしているWebページに特殊文字が含まれている可能性があるため、エンコードエラーが発生している可能性があります。 – gdlmx

答えて

2

ない `TypeError`あなたが主張する、あなたは` UnicodeEncodeError`を得る

f = codecs.open("test", "w", "utf-8", errors='ignore') 
+0

はい、動作しました。デバッグに関する何か:私はJavaコードを書くのに使っていましたが、Pythonの初心者です。あなたの助けを借りて、私はPythonのデバッグを進めてきたと思います。Javaをデバッグするときは、常に最初のエラーを解決しようとします。 Pythonでは最後に解決しようとします。右? – ZhaoGang

+0

あなたのトレースバックでこのメッセージを聞かなかったかもしれません:_ "(最近の最後の呼び出し)" _ – gdlmx

関連する問題