1. 保存要爬的网页,代码如下:
# method1
response = urlopen(url).read().decode('utf-8') #用utf-8解析
soup = BeautifulSoup(response, 'lxml')
print(soup.prettify())

# method2, 更推荐
response = requests.get(url)
soup = BeautifulSoup(response.content.decode('utf-8'),'lxml')
print(soup.prettify())

file_obj = open('chengdu_douban.html', 'w', encoding="utf-8")  # 以写模式打开名叫 douban.html的文件,指定编码为utf-8
file_obj.write(response.content.decode('utf-8'))  # 把响应的html内容存入
file_obj.close()  # 关闭文件,结束写入;

报错: ‘str’ object has no attribute ‘content’

Debug:用第一种方法urlopen的时候,respose已经decode了,不需要再decode。所以运行完method1之后,直接保存网页的话,就会报错。
file_obj.write(response.content.decode(‘utf-8’)) 可以改为 file_obj.write(response)
如果是运行完method2,这时response还没有decode,这时保存网页就没问题。

  1. 打开保存的网页的时候:
file_obj = open('chengdu_douban.html', 'r')  # 以读方式打开文件名为douban.html的文件
html = file_obj.read()  # 把文件的内容全部读取出来并赋值给html变量
file_obj.close()  # 关闭文件对象

soup = BeautifulSoup(html, 'lxml')  # 初始化BeautifulSoup

print(soup.prettify())

报错:‘gbk’ codec can’t decode byte 0xae in position 345: illegal multibyte sequence

Debug:在打开的时候也要注意编码方式,加上encoding

改为:

file_obj = open('chengdu_douban.html', 'r',encoding="utf-8")  # 以读方式打开文件名为douban.html的文件
html = file_obj.read()  # 把文件的内容全部读取出来并赋值给html变量
file_obj.close()  # 关闭文件对象

soup = BeautifulSoup(html, 'lxml')  # 初始化BeautifulSoup

print(soup.prettify())

无报错。

注意:
decode的时候:看网页的编码是什么,就用什么解码,在meta标签可以看
编码是什么:GBK包含全部中文字符;UTF-8则包含全世界所有国家需要用到的字符。

更多推荐

python 中 'str' object has no attribute 'content' 的报错解决