#目标,通过request来获取这个http://quotes.toscrape.com/网页上的所有名人名言

import requests

import os

if __name__ == "__main__":

# 1、指定url

url = "http://quotes.toscrape.com/"

#2、UA伪装

header = {

'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'

}

#3、发起请求

response = requests.get(url=url,headers=header)

#4、判断是否请求成功

if response.status_code == 200:

print("状态码为200就是获取成功:"+str(response))

# print(response.text)#这里可以选择不打印哦

page_text = response.text#为什么不直接使用 response.text

#响应文本存储在变量中的原因是为了更好地组织代码,为了在后续的代码中多次使用相同的文本内容而不需要重新发起请求。

# 5、数据持久化,就是把爬取到的文件保存下来

# 直接保存在当前脚本文件的相同目录中

custom_filename = '../test2/famous_saying.html'

fileName = os.path.join(os.path.abspath(os.path.dirname(__file__)), custom_filename)

with open(fileName, 'w', encoding='utf-8') as f:

f.write(page_text)

print(fileName, '保存成功')

else:

print(f"请求失败,状态码:{response.status_code}")

#'w' 表示以文本写模式打开文件。在这种模式下,如果文件不存在,则创建文件;

# 如果文件已存在,则截断文件(即清空文件内容),然后写入新的内容。这种模式用于处理文本文件。

# 'wb'表示以二进制写模式打开文件。在这种模式下,同样会创建文件或者截断文件,

# 但是它是以二进制方式进行操作,适用于处理非文本文件,比如图片、音频等二进制文件。

推荐文章

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。