Skip to content

urllib与requests

这一页的目标,是让你真正开始用 Python 发网络请求。

urllib

urllib 是 Python 自带的网络请求工具。
它更底层一些,写法也相对啰嗦,但理解它有助于你知道请求到底是怎么工作的。

requests

requests 是更常用、更友好的请求库。
在爬虫入门阶段,你大多数时候会先用它。

安装:

bash
pip install requests

最基础的 GET 请求

python
import requests

url = "https://httpbin.org/get"
response = requests.get(url)

print(response.status_code)
print(response.text)

如果请求成功,状态码通常是:

text
200

传 URL 参数

python
import requests

url = "https://httpbin.org/get"
params = {"kw": "python", "page": 1}

response = requests.get(url, params=params)
print(response.url)

输出可能像这样:

text
https://httpbin.org/get?kw=python&page=1

POST 请求

python
import requests

url = "https://httpbin.org/post"
data = {"username": "tom", "password": "123456"}

response = requests.post(url, data=data)
print(response.status_code)
print(response.text)

获取 JSON 响应

python
import requests

response = requests.get("https://httpbin.org/json")
print(response.json())

请求头

有些网站会检查请求头,例如:

  • User-Agent
  • Referer
  • Cookie
python
headers = {
    "User-Agent": "Mozilla/5.0"
}
response = requests.get(url, headers=headers)

很多登录态站点都和 Cookie、Session 有关。
如果你不理解它们,后面登录抓取会很容易失败。

代理设置

有些请求会用到代理,尤其在高频抓取和反爬场景中。

Built with VitePress.