爬取网站内容-学习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' 语句时,文件会在代码块结束时自动关闭
相关推荐
Tan38512 分钟前
如何在 OfficeAI 上配置 API Key(图文教程)
开发语言·人工智能·c#·api·教程·officeai
代码or搬砖4 分钟前
JVM学习笔记
jvm·笔记·学习
2301_8119583812 分钟前
服务器自己账号下安装conda
linux·python·conda
军军君0113 分钟前
Three.js基础功能学习二:场景图与材质
前端·javascript·学习·3d·材质·three·三维
百***787513 分钟前
Mistral 3极速接入指南:3步上手+核心能力解析+避坑手册
人工智能·python·开源
PM老周14 分钟前
产品路线图怎么做:从愿景到里程碑的 6 步落地法
开发语言·安全·阿里云·团队开发·个人开发
LCG米16 分钟前
嵌入式Python开发:MicroPython在物联网硬件上的实战应用案例
python·单片机·物联网
nvd1117 分钟前
SQLAlchemy 2.0 类型注解指南:`Mapped` 与 `mapped_column`
python
让学习成为一种生活方式19 分钟前
AGAT v1.6.0 安装与使用--生信工具72
人工智能·python·机器学习
南山星火20 分钟前
人工智能“学习”范式大全(24种)
人工智能·学习