response.status_code为418
当我使用Python的requests爬取网页时response和soup都是None,检查后发现response.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.
翻译为:HTTP 418 I’m a teapot客户端错误响应代码表示服务器拒绝煮咖啡,因为它是一个茶壶。这个错误是对1998年愚人节玩笑的超文本咖啡壶控制协议的引用。
当时用了requests库,没有添加请求头等信息,可能被反爬程序识别了,再次请求添加了header的User-Agent信息就可以了。
import requests
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'}
res = requests.get(url,headers=headers)
import requests
class DouBan:
def __init__(self, type):
'''
初始化方法,当创建一个类的对象的时候,该方法会被自动执行,不需要手动调用
'''
self.book_type = type
self.url = "https://book.douban.com/tag/"+self.book_type+"?start={}&type=T"
def get_urls(self):
'''该方法用来构造所有的url'''
# 列表生成式
return [self.url.format(20*i) for i in range(5)]
def parse_url(self, url):
'''发送请求并解析数据'''
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'}
response = requests.get(url, headers=headers)
return response.content.decode()
def save_data(self, content, page_count):
'''保存数据'''
file_name = '豆瓣图书-{}-第{}页.html'.format(self.book_type, page_count)
with open('./DouBan/' + file_name, 'w', encoding='utf-8') as f:
f.write(content)
def run(self):
'''爬虫程序启动'''
# 1. 构造url地址
request_list = self.get_urls()
# 2. 在地址池中进行遍历,每遍历出一个地址就像该地址发送请求,获取响应得到的内容
for url in request_list:
# 2.1 发送请求
html_content = self.parse_url(url)
# 2.2 二次提取网页中的数据
# 2.3 直接保存网页内容到本地
page_count = request_list.index(url) + 1
self.save_data(html_content, page_count)
if __name__ == '__main__':
# 1.创建爬虫对象
db = DouBan('小说')
# 2.启动爬虫程序
db.run()
读取文件内容:
# 读取文件内容并按换行符切分
lines = open("data/voc01.txt", encoding="utf-8").read().split("\n")
写入文件:
# 追加写入到指定文件
str = "abcd"
with open('E:/test/test_en.txt', mode='a+', encoding="utf-8") as w:
w.write(str + "\n")
1
with open("test.txt","w") as file:
file.write("hello")
2
file2 = open("test2.txt","w")
file2.write("hello2")
file2.close()
// close()别忘记()