继续写。
上一篇写了最简单的一个爬虫,这次我们改下url地址,换成糗百,修改完的代码如下:
from urllib.request import urlopen
# 发送请求,获取服务器给的响应
url = "https://www.qiushibaike.com/"
response = urlopen(url)
# 读取结果,无法正常显示中文
html = response.read()
# 进行解码操作,转为utf-8
html_decode = html.decode()
# 打印结果
print(html_decode)
执行下,会发现报错,raise RemoteDisconnected("Remote end closed connection without"http.client.RemoteDisconnected: Remote end closed connection without response)
什么意思?就是服务器拒绝爬虫请求,这时候我们需要模拟成一个浏览器,增加request 头信息,主要是设置user-agent,我们改动下代码,模拟成火狐浏览器
from urllib.request import urlopen
from urllib.request import Request
from fake_useragent import UserAgent
#设置request header
ua = UserAgent()
headers = {
"User-Agent":ua.firefox
}
#封装request
url = "https://www.qiushibaike.com/"
request = Request(url,headers=headers)
# 发送请求,获取服务器给的响应
response = urlopen(request)
# 读取结果,无法正常显示中文
html = response.read()
# 进行解码操作,转为utf-8
html_decode = html.decode()
# 打印结果
print(html_decode)
再执行就会发现成功了。