第一讲案例

本文通过五个实例详细介绍了Python爬虫的基本操作,包括获取百度首页产品大全、新浪新闻页、百度贴吧、百度首页及百度翻译的爬取。涉及到的关键技术包括观察请求URL、请求参数、请求头的设置以及处理Ajax请求。最后还提到了金山词霸的爬取挑战。
摘要由CSDN通过智能技术生成

第一例 百度首页产品大全

1、首先进入百度首页—>产品大全https://www.baidu.com/more/,获取爬取页面的url
首先进入百度首页,点击更多,进入产品大全页面。

然后通过F12或者右击选择“检查”,点击“Network”,选中“doc”格式文件。点击刷新,获取页面响应的doc文件,然后点击可以查看。
在这里插入图片描述
其中URL中是我们需要的请求url,Method就是这个页面的请求方式,这里是get
在这里插入图片描述
将获取到的url复制到浏览器中,若可以得到这个页面,说明操作正确。
2、创建.py文件,搭建基本架构。

# 导包
import requests

# 模拟发送请求,获取响应
response = requests.get(url='https://www.baidu.com/more/')
# 获取响应内容
print(response)
# 查看状态码
print(response.status_code)
# 查看响应头
print(response.headers)
# 问题:文本数据有哪两种格式?
# 字符串响应正文:
print(response.text)
# response.text是通过response.encoding这个属性设置的值来进行编程字符串
# response.encoding是通过requests模块自动识别的。(基本识别都是对的)
print(response.encoding)

# bytes响应正文:
print(response.content.decode(encoding='utf-8'))
# 将响应内容保存到本地
# with 上下文管理器,open,自动关闭
with open('index.html', 'w',encoding='utf-8') as fp:
    fp.write(response.content.decode(encoding='utf-8'))

# 更改response.encoding的编码方式,response.text以该方式进行识别。
response.encoding = 'utf-8'
with open('index2.html', 'w', encoding='utf-8') as fp:
    fp.write(response.text)

第二例 新浪新闻页

1、进入新浪官网搜索任意关键词,这里以“python”为例,得到新闻列表页。https://search.sina.com.cn/?q=python&c=news&from=index
按照上一案例操作,得到url以及其他响应信息。
在这里插入图片描述
通过红框中的内容获取页面请求参数,以键值对的形式保存到params变量中。

params = {
        "range": "all",
        "c": "news",
        'q': key_word,
    }

2、用户可以通过关键字获取不同的新闻页,因此需要实现该功能,需要观察请求的url,以下列出了“python”、“java”、“php”三个关键字请求的url

https://search.sina.com.cn/?q=python&range=all&c=news&sort=time
https://search.sina.com.cn/?q=java&range=all&c=news&sort=time
https://search.sina.com.cn/?q=php&range=all&c=news&sort=time

可以看出url中q值是和搜索的关键字相同,可以变更q的值获取不同的页面。可以尝试将q值改为“c++”在浏览器直接获取页面。
3、有两种操作方式可以获取该关键字下的新闻url序列:
(一)、使用关键字传参。

import requests


def p_1(key_word):
    # 确定基础url,?之前的内容
    base_url = 'https://search.sina.com.cn/?'
    # 准备参数字典
    params = {
        "range": "all",
        "c": "news",
        'q': key_word,
    }
    # 发送请求获取响应
    response = requests.get(url=base_url, params=params)

    with open(f'sina_{key_word}.html', 'w', encoding='utf-8') as fp:
        fp.write(response.content.decode(encoding="utf-8"))

(二)、使用字符串拼接

def p_2(kew_word):
   """拼接url"""
   base_url = 'https://search.sina.com.cn/?q=%s&c=news&from=channel&ie=utf-8'
   # 发送请求获取响应
   response = requests.get(url=base_url % key_word)
   print(base_url % key_word)

   with open(f'sina_{key_word}.html', 'w', encoding='utf-8') as fp:
       fp.write(response.content.decode(encoding="utf-8"))

上述代码使用了函数进行了封装,需要在程序入口调用执行。

if __name__ == "__main__":
   key_word = input('请输入爬取的新闻关键字:')
   p_1(key_word)
   p_2(key_word)

第三例 百度贴吧

1、访问百度贴吧,输入关键字搜索,和上一案例操作相同。
同样以“python”为例,https://tieba.baidu.com/f?ie=utf-8&kw=python&fr=search
2、贴吧列表列不只一页,可查看每一页的内容,将url保存起来,进行比较。这里复制了前三页url,第一页可能有所不同,但不影响。

https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=0
https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=50
https://tieba.baidu.com/f?kw=python&ie=utf-8&pn=100

可以看出最后pn参数是50倍的关系,就得到了每一页url变化的规律。
3、通过url拼接,发送请求获取响应,完整代码如下:

import requests
import os


def tieba(key_word, page):
    """
    爬取贴吧
    :param key_word: 关键字
    :param page: 页码
    :return:
    """
    # 确定url
    base_url = "https://tieba.baidu.com/f?"
    # 确定参数
    params = {
        "kw": key_word,
        "ie": "utf-8",
        "pn": (page - 1) * 50,
    }

    # 发送请求获取响应
    response = requests.get(base_url, params=params)

    # 创建保存路径
    dirname = f'./tieba/{key_word}'
    if not os.path.exists(dirname):
        os.mkdir(dirname)
    # 写入文件
    with open(f'{dirname}/{page}.html', 'w', encoding='utf-8') as fp:
        fp.write(response.content.decode(encoding='utf-8'))


if __name__ == '__main__':
    key_word = input("请输入爬取内容的关键字:")
    for page in range(1,11):
        tieba(key_word, page)
        

第四例 百度首页

1、如果按照上述方法爬取百度首页,会发现并不能得到想要的页面内容,这是因为百度首页会自动识别请求者的身份,在没有任何伪装的情况下直接辨认出请求身份为爬虫,百度服务器拒绝访问。这是我们想要在请求的时候伪装成浏览器,进行的操作是添加请求头。
在这里插入图片描述
User-Agent:是客户浏览器的名称
2、使用字典形式存储请求头,并在请求时传入headers参数中。

import requests

# 确定url
base_url = 'https://www.baidu.com/'

# 确定请求头
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36',

}
# 发送请求获取响应
response = requests.get(base_url, headers=headers)

print(response.content.decode('utf-8'))

第五例 百度翻译

1、百度翻译跟上述案例有明显不同,首先是响应文件不再是doc格式,而是Ajax请求的XRL格式。
这里,将一个方便查找的操作,点击清空按钮,将响应文件清空,在图中标识。选中XHR,在输入框中输入单词,可以看到有文件刷出,点击进行查看。
在这里插入图片描述
怎样确认是我们需要的文件呢,这里,我们可以点击“preview”查看数据。
在这里插入图片描述
在第一张图中可以看出该文件的请求方式是post请求,引起需要调用的是requests模块中的post方法,参数变量为data。

import requests


def translate_word(kew_word):
    """爬取百度翻译的结果"""
    # 确定url
    base_url = 'https://fanyi.baidu.com/sug'
    # 准备参数
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.92 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest',  #ajax必须添加
        'content-length': str(len(kew_word)+3),
        'ent-type': 'application/x-www-form-urlencoded; charset=UTF-8'
    }
    data = {
        'kw': kew_word
    }

    # 发送请求获取响应
    response = requests.post(base_url, headers=headers, data=data)
    # print(response.json())
    return response.json()['data']



def main():
    """爬取思路"""
    # 1、输入单词
    key_word = input("请输入要翻译的单词:")
    # 2、调用函数获取结果
    result = translate_word(key_word)
    ret = ''
    for i in result:
        ret += i['v'] + '\n'
    print(ret)
    # 3、输出结果
    return


if __name__ == '__main__':
    main()

上述代码中添加了四个请求头,是post一般需要添加的。
3、post请求获取的响应内容格式为json数据,需要转换为字典和列表形式,使用了requests模块自带的json()方法。
最后将数据以想要的形式进行了输出。

扩展案例 金山词霸


亲测,只支持该页面下的翻译,请勿回车
有兴趣的可以爬爬试试,感谢阅读。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值