自学内容网 自学内容网

[数据采集技术:实践01]:urlLib包urlopen()和requests 的 get()方法和 PoolManager 对象的使用

要求说明

数据采集技术实验一(网络访问请求与响应) 1.创建项目文件夹,命名为:学号-1,如:20220001-1。后续所有文
件均放在此文件夹中。

urllib包urlopen()方法的使用

2.新建 test1.py 文件,使用 urllib 的 urlopen()方法,实现
对’https://www.python.org/’发起一个 get 网络请求,并显示响
应状态码,响应头的所有信息,Python 官网 HTML 代码。
3.新建 test2.py 文件,使用 urllib 的 urlopen()方法,实现
对’https://www.httpbin.org/post’发起一个 post 网络请求,参 数 data 为’university:sou’,显示响应的 HTML 代码。

test01

import urllib.request
url = 'https://www.python.org/'
try:
    response = urllib.request.urlopen(url)
    print("响应状态码:", response.status)
    print("响应头信息:")
    for key, value in response.getheaders().items():
        print(f"{key}: {value}")

    html_code = response.read().decode('utf-8')
    print("\nPython 官网 HTML 代码:")
    print(html_code[:1000])

except Exception as e:
    print("请求失败:", e)

test02

import urllib.request
import urllib.parse

url = 'https://www.httpbin.org/post'
data = urllib.parse.urlencode({'university': 'sou'}).encode('utf-8')

try:
    response = urllib.request.urlopen(url, data = data)
    html_code = response.read().decode('utf-8')
    print("相应的HTML代码")
    print(html_code)
except Exception as e:
    print("请求失败: ", e)

urllib3包PoolManager 对象的使用

4.新建 test3.py 文件,使用 urllib3 的 PoolManager 对象,实现向
京东、百度和 python 官网等多服务器发出 get 网络请求,并显示请
求状态码。
5.新建 test4.py 文件,使用 urllib3 的 PoolManager 对象,实现
对’https://www.httpbin.org/get’发起一个 get 网络请求,利用
HTTPResponse 对象,获取并显示 HTTP 响应头信息。

test03

import urllib3

http = urllib3.PoolManager()

urls = [
    'https://www.jd.com/',
    'https://www.baidu.com/',
    'https://www.python.org/'
]

for  url in urls:
    try:
        response = http.request('GET', url)
        print(f"请求: {url} 的状态码: {response.status}")
    except Exception as e:
        print(f"请求 {url} 失败: {e}")

test04

import urllib3

http = urllib3.PoolManager()

url = 'https://www.httpbin.org/get'
try:

    response = http.request('GET', url)
    print("HTTP 请求头信息")
    for key, value in response.headers.items():
        print(f"{key}: {value}")

except Exception as e:
    print("请求失败:", e)

requests 的 get()方法的使用

6.新建 test5.py 文件,使用 requests 的 get()方法,添加请求头,
实现对’https://www.baidu.com/’发起一个 get 网络请求,获取并
显示响应状态码

test05

import requests

url = 'https://www.baidu.com'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}

try:
    response = requests.get(url, headers=headers)
    print("响应状态码:", response.status_code)
except Exception as e:
    print("请求失败:", e)

原文地址:https://blog.csdn.net/Abraxs/article/details/142907183

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!