爬取网站内容-学习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' 语句时,文件会在代码块结束时自动关闭
相关推荐
杨福瑞16 分钟前
C语⾔内存函数
c语言·开发语言
深耕AI17 分钟前
【PyTorch训练】准确率计算(代码片段拆解)
人工智能·pytorch·python
eqwaak022 分钟前
科技信息差(9.12)
开发语言·python·科技·量子计算
axban28 分钟前
QT M/V架构开发实战:QStringListModel介绍
开发语言·数据库·qt
茯苓gao30 分钟前
STM32G4 电流环闭环
笔记·stm32·单片机·嵌入式硬件·学习
刘媚-海外36 分钟前
Go语言开发AI应用
开发语言·人工智能·golang·go
easy202039 分钟前
机器学习的本质:从跑模型到真正解决问题
笔记·学习·机器学习
Blossom.1181 小时前
从“能写”到“能干活”:大模型工具调用(Function-Calling)的工程化落地指南
数据库·人工智能·python·深度学习·机器学习·计算机视觉·oracle
勇敢牛牛_1 小时前
使用Rust实现服务配置/注册中心
开发语言·后端·rust·注册中心·配置中心