爬取网站内容-学习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' 语句时,文件会在代码块结束时自动关闭
相关推荐
小羊羔heihei6 分钟前
Python列表操作全攻略
经验分享·笔记·python·学习·其他·交友
源码潇潇和逸逸8 分钟前
独立部署高校圈子平台:PHP+UniApp打造社交+交易+服务一站式校园解决方案
开发语言·uni-app·php
2501_9083298510 分钟前
实战:用OpenCV和Python进行人脸识别
jvm·数据库·python
LINgZone216 分钟前
深入解析:Cglib与JDK动态代理的实现原理、区别及性能对比
java·开发语言
一次旅行16 分钟前
今日心理学知识分享(三)
开发语言·javascript·程序人生·ecmascript
AI科技星36 分钟前
光速螺旋量子几何统一场论——基于 v ≡ c 公理的四大基本力全维度求导证明与精准数值验证
c语言·开发语言·人工智能·算法·机器学习·平面
天天学IT41 分钟前
第三章 Qt 编译及安装
开发语言·qt·qt教程·qt6教程
xyq202442 分钟前
Window Memcached 安装指南
开发语言
牛十二44 分钟前
openclaw安装mcporter搜索小红书
开发语言·javascript·ecmascript
老刘说AI1 小时前
WorkFlow Agent案例:auto_document_agent(文件自动处理)
开发语言·数据库·人工智能·python·神经网络·自然语言处理