爬取网站内容-学习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' 语句时,文件会在代码块结束时自动关闭
相关推荐
JustDI-CM4 分钟前
AI学习笔记-提示词工程
人工智能·笔记·学习
春日见4 分钟前
如何创建一个PR
运维·开发语言·windows·git·docker·容器
悟纤5 分钟前
学习与专注音乐流派 (Study & Focus Music):AI 音乐创作终极指南 | Suno高级篇 | 第33篇
大数据·人工智能·深度学习·学习·suno·suno api
爱写bug的野原新之助5 分钟前
加密摘要算法MD5、SHA、HMAC:学习笔记
笔记·学习
爱吃泡芙的小白白6 分钟前
环境数据多维关系探索利器:Pairs Plot 完全指南
python·信息可视化·数据分析·环境领域·pairs plot
C++ 老炮儿的技术栈8 分钟前
VS2015 + Qt 实现图形化Hello World(详细步骤)
c语言·开发语言·c++·windows·qt
派葛穆14 分钟前
Python-批量安装依赖
开发语言·python
pchaoda15 分钟前
RSI与布林带技术指标实战
python·matplotlib·量化
番茄灭世神21 分钟前
Python从入门到精通 第一章
python