前言

先在 Pycharm 安装 requests 包:

file -> Settings... -> Project:xxxxx -> Python Interpreter

 

二、示例代码与结果

#!/usr/bin/env python
# -*- coding: UTF-8 -*-

# 需求:爬取搜狗首页的页面数据

# noinspection PyUnresolvedReferences
import requests

if __name__ == '__main__':
    #UA伪装:将访问对象伪装为浏览器
    headers={
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36'
    }
    #爬虫主体
    # 1. 指定url
    url = 'https://www.sogou.com/'
    # 2. 发起请求(get方法会返回一个响应对象,我们把它存到 response 里)
    response = requests.get(url=url)
    # 3. 获取相应对象(text返回的是字符串形式的响应数据)
    page_text = response.text
    print(page_text)
    # 4. 持久化存储
    with open('./sougou.html', 'w', encoding='utf-8')as fp:
        fp.write(page_text)
        print('爬取数据结束!')

结果:

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐