gpt4 book ai didi

Python Beautifulsoup : file. write(str) 方法获取 TypeError : write() argument must be str, 不是 BeautifulSoup

转载 作者:行者123 更新时间:2023-11-30 22:56:56 26 4
gpt4 key购买 nike

我写了下面的代码:

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()

哪个编译器给出以下错误:

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>

但是 soup_string 显然是一个 str,那么为什么编译器给出第一个错误? 也不知道为什么会出现第二个。

如果我将代码更改为:

,会更困惑吗?
baseUrl = "https://ecurep.mainz.de.xxx.com/ae5/"
#baseUrl = "http://www.bing.com"
#baseUrl = "http://www.sohu.com/"

它会编译并且没有错误。 (我已将原来的名称更改为“xxx”)。

谁能帮忙调试一下吗?

更新:

我以前写过 Java 代码,现在是 Python 新手。在你的帮助下,我想我在调试Python方面取得了一些进展:调试Java时,总是尝试解决第一个错误;而在Python中,总是试图解决最后一个问题。

最佳答案

尝试使用 utf-8 打开文件

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

您可以通过

忽略编码错误(不推荐)
f = codecs.open("test", "w", "utf-8", errors='ignore')

关于Python Beautifulsoup : file. write(str) 方法获取 TypeError : write() argument must be str, 不是 BeautifulSoup,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36887065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com