解决Python爬取百度页面出现中文乱码问题 | 您所在的位置:网站首页 › 百度搜索结果变少了怎么办啊 › 解决Python爬取百度页面出现中文乱码问题 |
开始跟着B站上学习爬虫,使用的工具是PyCharm。
视频链接:https://b23.tv/NLp4gz6?share_medium=android&share_source=qq&bbid=XYC5605C8F19F10D959B8A59F386FD514EF41&ts=1640697988835
爬虫代码如下:
# -*- coding: utf-8 -*-
# 爬虫:本质是通过 编写程序 来获取到互联网上的资源
# 百度
# 需求:用程序模拟浏览器,输入一个网址,从该网址中获取到资源或内容
from urllib.request import urlopen # request表示请求库, urlopen打开一个网址
url = "http://www.baidu.com"
resp = urlopen(url) # 打开网址,得到响应
# resp.read() # 从响应中读取内容
# print(resp.read()) # b''表示字节
# print(resp.read().decode("utf-8"))
with open("mybaidu.html", mode="w") as f:
f.write(resp.read().decode("utf-8"))
print("over!")
运行成功后,打开爬取到的html页面: ![]() ![]() ![]() ![]() 最后想到去掉decode(“utf-8”)的同时,再将w模式改成wb模式,wb模式写入的就是字节类型。 |
CopyRight 2018-2019 实验室设备网 版权所有 |