[Python3] 爬取百度搜索内容页广告均数

本段代码用于对key_word.txt中的搜索词进行百度搜索,获取百度内容页(首页)的推广广告数。
其中为了防止特例偏差,所以每个关键词爬取了10次,并取均值作为最终展示的广告数量。

主要运用的Beautifulsoup函数库,爬取代码在request函数中.
Beautifulsoup手册:https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html

import requests
from bs4 import BeautifulSoup
from itertools import repeat

# 发送HTTP请求时的HEAD信息,用于伪装为浏览器
headersParameters = {
        'Connection': 'Keep-Alive',
        'Accept': 'text/html, application/xhtml+xml, */*',
        'Accept-Language': 'en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.3',
        'Accept-Encoding': 'gzip, deflate',
        'User-Agent': 'Mozilla/6.1 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko'
}

#迭代取均值
def develop(line):
    count = 0
    for i in range(10):
        count = request(line,count)

    num = count/10
    print("关键词:" + line + "\t总广告数:", count)
    data.write(line + "\t" + str(num) + "\n")

#爬取整理
def request(key_word,count):
    httpRsp = requests.get("http://www.baidu.com/s?wd="+key_word, headers=headersParameters)
    # httpResult = requests.get("https://www.zxxblog.cn", headers=headersParameters)
    # print(httpRsp.text)
    if httpRsp.status_code != 200:
        print("数据获取失败")
    else:
        soup = BeautifulSoup(httpRsp.text, "lxml")
        result = soup.find_all('span')
        #print(soup.prettify())
        for arr in result:
            if "广告" in arr:
                count = count + 1

        return count

#MAIN方法
if __name__=="__main__":
    data = open('data.txt', 'w+', encoding='utf-8')
    file = open('key_word.txt', 'r', encoding='utf-8')
    data.write("关键词\t广告均数\n")

    for line in file:
        line = line.strip('\n')
        develop(line)

    #END
    file.close()
    data.close()

最后,感谢在网上冲浪分享技术的GGMM们
参考教程:浅书 https://www.zxxblog.cn/article/92

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值