爬取网站内容-学习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' 语句时,文件会在代码块结束时自动关闭
相关推荐
风落青芜15 分钟前
C++入门:类和对象(三)
开发语言·数据结构·c++·算法
m0_6464299720 分钟前
LangGraph 学习笔记(一):StateGraph 与状态管理
python·langgraph
Dmz丶21 分钟前
前端转 AI 100 天 Day 57:RAG 项目实战(六)——上线后迭代,从“能用”到“越用越好”
python
AI2中文网30 分钟前
App Inventor 做的表单怎么导出 PDF?WebViewer + JavaScript 在本地生成并保存 PDF 的完整示例
android·开发语言·javascript·pdf·鸿蒙·app inventor
安教安全员通关宝39 分钟前
学习笔记:安全员A证、B证、C证的区别与适用岗位
笔记·学习·安全·题库·安全员c·安全员考试
Nerd(BUG版)1 小时前
Flutter学习day19--MethodChannel打通Dart与原生
学习·flutter
野生技术架构师1 小时前
高级 Java 工程师面试八股(2026 精选版)
java·开发语言·面试
小小-猿1 小时前
用 Python 写昇腾算子:pyasc 是怎么回事
开发语言·python·昇腾·cann·pyasc
星夜离尘561 小时前
MATLAB:标定表局部倒退,为什么不能排序?
android·开发语言·matlab
智购科技智能售货柜1 小时前
自动售货机步进电机细分驱动实战:力矩、噪声与堵转~YH
大数据·开发语言·人工智能·科技·嵌入式硬件