# urlib 获取网页(2) with header

将 url 对应的网页下载到本地

```python
# -*- coding: UTF-8 -*-
import urllib.request

def get_html(url, headers):
    # TODO(You): 请在此实现带头部信息的网页请求
    return html

if __name__ == '__main__':
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36"
    }
    url = "http://www.baidu.com"
    html = get_html(url, headers)
    print(html)
```

请选出下列能**正确**实现这一功能的选项。

## template

```python
import urllib.request

def get_html(url, headers=None):
    req = urllib.request.Request(url)
    if headers is not None:
        for key in headers:
            req.add_header(key, headers[key])
    response = urllib.request.urlopen(req)
    buff = response.read()
    html = buff.decode("utf8")
    return html

if __name__ == '__main__':
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36"
    }
    url = "http://www.baidu.com"
    html = get_html(url, headers)
    print(html)
```

## 答案

```python
def get_html(url, headers):
    req = urllib.request.Request(url)
    for key in headers:
        req.add_header(key, headers[key])
    response = urllib.request.urlopen(req)
    buff = response.read()
    html = buff.decode("utf8")
    return html
```

## 选项

### A

```python
def get_html(url, headers):
    req = urllib.request.Request(url)
    for key in headers:
        urllib.request.add_header(key, headers[key])
    response = urllib.request.urlopen(req)
    buff = response.read()
    html = buff.decode("utf8")
    return html
```

### B

```python
def get_html(url, headers):
    req = urllib.request.urlopen(url)
    for key in headers:
        req.add_header(key, headers[key])
    response = urllib.request.urlopen(req)
    buff = response.read()
    html = buff.decode("utf8")
    return html
```

### C

```python
def get_html(url, headers):
    req = urllib.request.Request(url)
    for key in headers:
        req.set_header(key, headers[key])
    response = urllib.request.urlopen(req)
    buff = response.read()
    html = buff.decode("utf8")
    return html
```
