Python美容组:文件.写入(str)方法获取类型错误:write()参数必须是str,而不是BeautifulSoup

2024-04-29 13:11:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我写了以下代码:

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

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

^{pr2}$

但是soup_字符串显然是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中,总是试图解决最后一个错误。在


Tags: 代码importcomhttpishtmlwww错误