python requests.get报错_【零基础直接干python】requests.get(url)返回的status_code=418的错误...

看了点儿简单的python基础,直接干实例,毕竟我自学能力差,一点点儿看基础,看了还是什么也不会,永远只会print()……

于是直接干实例,不懂的问题再搜索。

仿着例子做爬虫。是爬去热榜书名,很简单的爬虫。就像一些大神说的,只要用好了requests和beautifulsoup就基本可以爬一些“简单”的网站了。

我哪儿知道他简单不简单?

于是就遇到了问题。

import requests

from bs4 import BeautifulSoup

import time

num = 1 ##计数

start_time = time.time()

url = 'https://read.douban.com/charts?type=long_finalized&index=featured&dcs=charts&dcm=chart-card-more'

html = requests.get(url,headers = headers)

print(html.status_code)

soup = BeautifulSoup(html.content,'html.parser')

print(soup.prettify())

book_list = soup.find_all('h4',attrs = {'class':'title'})

for book in book_list:

node = book.contents[0]

title = node.contents[0]

print(title)

name = '<>'

print = ('第%d本书'%num,name)

num = num + 1

time.sleep(1)

end_time = time.time()

duration_time = end_time - start_time

print('运行时间:%.2f'%duration_time + '秒')

运行之,就发现了status_code=418。怪不得程序不往下走。

百度之,这个问题不多啊。直接搜status_code出现的问题,没有418。

才知道,貌似这是网站为了反爬虫,设置的。

经过网上查询得知,418的意思是被网站的反爬程序返回的,网上解释为,418 I’m a teapot

The HTTP 418 I’m a teapot client error response code indicates that the server refuses to brew coffee because it is a teapot. This error is a reference to Hyper Text Coffee Pot Control Protocol which was an April Fools’ joke in 1998.

解决办法:

当时用了requests库,没有添加请求头等信息,可能被反爬程序识别了,再次请求添加了header的User-Agent信息就可以了。

我就加了下面一段,虽然我根本不懂!

headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'}

html = requests.get(url,headers = headers)

就解决了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值