爬取网站内容-学习01

目录

说明:

爬取网站页面的相关内容

简述

工具条件

工具:Visual Studio Code,PyCharm 2023.2.1

语言:python

库 :requerts

requests

requests是Python中一个流行的HTTP客户端库,用于发送所有类型的HTTP请求。它简单易用,功能强大,支持多线程,并且有多种身份验证和cookie处理机制。

requests不是Python标准库的一部分,需要使用pip install requests来安装。

GET请求:

python 复制代码
import requests

response = requests.get('https://www.example.com')
print(response.text)

POST请求:

python 复制代码
import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://www.example.com', data=payload)
print(response.text)

POST请求带JSON数据

python 复制代码
import requests

payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://www.example.com/api', json=payload)
print(response.text)

自定义请求头

python 复制代码
import requests

headers = {'User-Agent': 'my-app/0.0.1'}
response = requests.get('https://www.example.com', headers=headers)
print(response.text)

爬取网站相关内容,确定需要的网址,现以www.baidu.com为例;

代码

python 复制代码
import requests

def simple_crawler(url):
    try:
        response = requests.get(url)
        response.raise_for_status()
        response.encoding = response.apparent_encoding
        return response.text
    except requests.exceptions.RequestException as err:
        print("Error: ", err)
        return None

if __name__ == "__main__":
    url = "https://www.baidu.com"  #替换成要爬取的网页URL
    content = simple_crawler(url)
    if content:
        print(content)
        
    # 打开一个文件以写入,如果文件不存在,它将被创建
    # 'w' 参数表示写入模式
    with open('output.txt', 'w') as file:
        # 写入一些文本到文件
        file.write(content)

  # 当您使用 'with' 语句时,文件会在代码块结束时自动关闭
相关推荐
Bruce_Liuxiaowei5 分钟前
PHP文件包含漏洞详解:原理、利用与防御
开发语言·网络安全·php·文件包含
泽020214 分钟前
C++之STL--list
开发语言·c++·list
YGGP18 分钟前
吃透 Golang 基础:数据结构之 Map
开发语言·数据结构·golang
~plus~20 分钟前
Harmony核心:动态方法修补与.NET游戏Mod开发
开发语言·jvm·经验分享·后端·程序人生·c#
步、步、为营27 分钟前
.NET 事件模式举例介绍
java·开发语言·.net
程序猿tu28 分钟前
Axios学习笔记
笔记·学习
~plus~30 分钟前
WPF八大法则:告别模态窗口卡顿
开发语言·经验分享·后端·程序人生·c#
march of Time40 分钟前
go工具库:hertz api框架 hertz client的使用
开发语言·golang·iphone
有谁看见我的剑了?1 小时前
stress 服务器压力测试的工具学习
服务器·学习·压力测试
有谁看见我的剑了?1 小时前
stress-ng 服务器压力测试的工具学习
服务器·学习·压力测试