python爬虫代码怎么运行_零基础学python爬虫

python爬虫代码怎么运行_零基础学python爬虫在 Python 中 发送 HTTP 请求通常使用 requests 库 它是一个简单易用的第三方库 可以通过 pip 进行安装 pip install requests 安装完成后 你可以使用 requests 库发送不同类型的 HTTP 请求 例如 GET POST 等 以下是一些基本的示例 GET 请求 pythonimport requests 发送 GET 请求 response

在Python中,发送HTTP请求通常使用`requests`库,它是一个简单易用的第三方库,可以通过`pip`进行安装:

pip install requests

安装完成后,你可以使用`requests`库发送不同类型的HTTP请求,例如GET、POST等。以下是一些基本的示例:

GET请求

python

import requests

发送GET请求

response = requests.get('http://example.com')

打印状态码、头信息和内容

print(response.status_code)

print(response.headers)

print(response.text)

POST请求

python

import requests

发送POST请求

data = {'key': 'value'}

response = requests.post('http://example.com/post', data=data)

打印状态码、头信息和内容

print(response.status_code)

print(response.headers)

print(response.text)

添加请求头

python

import requests

headers = {

'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}

response = requests.get('http://example.com', headers=headers)

打印状态码、头信息和内容

print(response.status_code)

print(response.headers)

print(response.text)

处理Cookies和重定向

python

import requests

发送GET请求,并处理Cookies

cookies = {'cookie_name': 'cookie_value'}

response = requests.get('http://example.com', cookies=cookies)

打印状态码、头信息和内容

print(response.status_code)

print(response.headers)

print(response.text)

发送POST请求,并处理重定向

response = requests.post('http://example.com/post', data=data, allow_redirects=True)

打印状态码、头信息和内容

print(response.status_code)

print(response.headers)

print(response.text)

使用`urllib`库

如果你更倾向于使用Python标准库`urllib`,你也可以发送HTTP请求。以下是使用`urllib`发送GET请求的示例:

python

from urllib.request import urlopen

发送GET请求

response = urlopen('http://example.com')

读取响应内容并打印

print(response.read().decode('utf-8'))

使用`urllib`时,你可能需要处理更多的细节,比如授权验证、重定向处理等。

请根据你的具体需求选择合适的库和方法。

编程小号
上一篇 2025-06-13 22:14
下一篇 2026-04-20 08:39

相关推荐

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/54625.html