2023-01-30 17:51:18 +08:00

177 lines
7.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

本节介绍如何访问网页。
# ✔️ 浏览器访问网页
`ChromiumPage``WebPage`的 d 模式用于控制浏览器,使用`get()`方法访问网页。
## 📍 `get()`方法
该方法用于跳转到一个网址。
当连接失败时,程序默认重试 3 次,每次间隔 2 秒,可以通过参数设置重试次数和间隔。
| 参数名称 | 类型 | 默认值 | 说明 |
|:-------------:|:-------:|:-------:| --------------------------- |
| `url` | `str` | 无 | 目标url |
| `show_errmsg` | `bool` | `False` | 连接出错时是否显示和抛出异常 |
| `retry` | `int` | `None` | 重试次数,为`None`时使用页面参数,默认 3 |
| `interval` | `float` | `None` | 重试间隔(秒),为`None`时使用页面参数,默认 2 |
| `timeout` | `float` | `None` | 加载超时时间(秒) |
| 返回类型 | 说明 |
|:------:| ----- |
| `bool` | 否连接成功 |
**示例:**
```python
from DrissionPage import WebPage
page = WebPage()
page.get('https://www.baidu.com')
```
## 📍 设置超时时间和重试参数
网络不稳定时访问页面不一定成功,`get()`方法内置了超时和重试功能。通过`retry``interval``timeout`三个参数进行设置。
其中,如不指定`timeout`参数,该参数会使用`WebPage``timeouts`属性的`page_load`参数中的值。
```python
from DrissionPage import WebPage
page = WebPage()
page.get('https://www.163.com', retry=1, interval=1, timeout=1.5)
```
## 📍 设置加载策略
通过设置`WebPage`对象的`page_load_strategy`属性,可设置页面停止加载的时机。页面加载时,在到达超时时间,或达到设定的状态,就会停止,可有效节省采集时间。有以下三种模式:
- `'normal'`:常规模式,会等待页面加载完毕。
- `'eager'`:加载完 DOM 即停止加载。
- `'none'`:完成连接即停止加载。
默认设置为`'normal'`
```python
from DrissionPage import WebPage
page = WebPage()
page.set_page_load_strategy()
```
# ✔️ 数据包访问网页
`SessionPage``WebPage`的 s 模式基于 requests因此可使用 requests 内置的所有请求方式,包括`get()``post()``head()``options()``put()``patch()``delete()`
。不过本库目前只对`get()``post()`做了封装和优化,其余方式可通过调用页面对象内置的`Session`对象调用。
## 📍 `get()`方法
`get()`方法使用语法与 requests 的`get()`方法一致,在此基础上增加了重试设置参数。
| 参数名称 | 类型 | 默认值 | 说明 |
|:-------------:|:-------:|:-------:| --------------------------- |
| `url` | `str` | 无 | 目标url |
| `show_errmsg` | `bool` | `False` | 连接出错时是否显示和抛出异常 |
| `retry` | `int` | `None` | 重试次数,为`None`时使用页面参数,默认 3 |
| `interval` | `float` | `None` | 重试间隔(秒),为`None`时使用页面参数,默认 2 |
| `timeout` | `float` | `None` | 加载超时时间(秒) |
| `**kwargs` | - | `None` | 连接所需其它参数,具体见 requests 用法 |
| 返回类型 | 说明 |
|:------:| ----- |
| `bool` | 否连接成功 |
`**kwargs`参数与 requests 中该参数使用方法一致,但有一个特点,如果该参数中设置了某一项(如`headers`),该项中的每个项会覆盖从配置中读取的同名项,而不会整个覆盖。
就是说,如果想继续使用配置中的`headers`信息,而只想修改其中一项,只需要传入该项的值即可。这样可以简化代码逻辑。
与 requests 不一样,`get()`方法不返回`Response`对象以获取结果,处理返回结果的方式详见后面章节。
实用功能:
- 程序会根据要访问的网址自动在`headers`中加入`Host``Referer`
- 程序会自动从返回内容中确定编码,一般情况无须手动设置
```python
from DrissionPage import WebPage
page = WebPage('s')
url = 'https://www.baidu.com'
headers = {'referer': 'gitee.com'}
cookies = {'name': 'value'}
proxies = {'http': '127.0.0.1:1080', 'https': '127.0.0.1:1080'}
page.get(url, headers=headers, cookies=cookies, proxies=proxies)
```
?> s 模式访问时默认设置`redirect`参数为`False`,即访问重定向链接时须手动处理。
## 📍 `post()`方法
此方法是用 post 方式请求页面。用法与`get()`一致。调用时,`WebPage`对象会自动切换到 s 模式。
| 参数名称 | 类型 | 默认值 | 说明 |
|:-------------:|:---------------:|:-------:| --------------------------- |
| `url` | `str` | 无 | 目标url |
| `data` | `dict`<br>`str` | `None` | 提交的数据 |
| `json` | `dict`<br>`str` | `None` | 提交的数据 |
| `show_errmsg` | `bool` | `False` | 连接出错时是否显示和抛出异常 |
| `retry` | `int` | `None` | 重试次数,为`None`时使用页面参数,默认 3 |
| `interval` | `float` | `None` | 重试间隔(秒),为`None`时使用页面参数,默认 2 |
| `timeout` | `float` | `None` | 加载超时时间(秒) |
| `**kwargs` | - | `None` | 连接所需其它参数,具体见 requests 用法 |
| 返回类型 | 说明 |
|:------:| ----- |
| `bool` | 否连接成功 |
```python
from DrissionPage import WebPage
page = WebPage('s')
data = {'username': 'xxxxx', 'pwd': 'xxxxx'}
page.post('http://example.com', data=data)
# 或
page.post('http://example.com', json=data)
```
`data`参数和`json`参数都可接收`str``dict`格式数据,即有以下 4 种传递数据的方式:
```python
# 向 data 参数传入字符串
page.post(url, data='abc=123')
# 向 data 参数传入字典
page.post(url, data={'abc': '123'})
# 向 json 参数传入字符串
page.post(url, json='abc=123')
# 向 json 参数传入字典
page.post(url, json={'abc': '123'})
```
具体使用哪种,按服务器要求而定。
## 📍 其它请求方式
本库只针对常用的 get 和 post 方式作了优化,但也可以通过提取页面对象内的`Session`对象以原生 requests 代码方式执行其它请求方式。当然,它们工作在 s 模式。
```python
from DrissionPage import WebPage
page = WebPage('s')
# 获取内置的 Session 对象
session = page.session
# 以 head 方式发送请求
response = session.head('https://www.baidu.com')
print(response.headers)
```
输出:
```shell
{'Accept-Ranges': 'bytes', 'Cache-Control': 'private, no-cache, no-store, proxy-revalidate, no-transform', 'Connection': 'keep-alive', 'Content-Length': '277', 'Content-Type': 'text/html', 'Date': 'Tue, 04 Jan 2022 06:49:18 GMT', 'Etag': '"575e1f72-115"', 'Last-Modified': 'Mon, 13 Jun 2016 02:50:26 GMT', 'Pragma': 'no-cache', 'Server': 'bfe/1.0.8.18'}
```