python3 ---requests库 --- User-Agent使用

import requests
# url = 'https://www.baidu.com'
url = 'https://www.xicidaili.com/nn'

headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4146.4 Safari/537.36'
}
res = requests.get(url=url, headers=headers)
# 获取响应状态码
code = res.status_code
print(code)
# 响应成功后,把响应内容写入文件中
if code == 200:
    with open('./test.html', 'w', encoding='utf-8') as fp:
        fp.write(res.text)

你可能感兴趣的:(python)