# coding = utf-8
'''根据页面标题和URL判断百度搜索结果(SERP)前三页是否存在,从而判断网址是否被百度收录。'''
#导入http请求库request
import requests
#导入随机数库
import random
# 导入URL解析库
from urllib import parse
# 导入BeautifulSoup库,使用别名bs
from bs4 import BeautifulSoup as bs
# @item_title 代表需要查询的网址标题,@item_url代表要查询的网址,@page代表查询百度前几页的结果,默认前3页
def get(item_title, item_url, page = 3):
serp_list = []
# 对关键词进行URLencode
word = parse.quote_plus(item_title)
# 拼接待查询网址
for pn in range(1, page + 1):
# 百度分页样例 第二页 https://www.baidu.com/s?ie=utf-8&wd=python&pn=10
url = 'https://www.baidu.com/s?ie=utf-8&wd=' + word + '&pn=' + str((pn-1)*10)
headers = {}
headers['User-Agent'] = "Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0" + str(random.randint(1,99))
headers['Referer'] = url
# 超时设为10秒,如果网页10秒内无响应抛出异常
timeout = 10
# 发送请求
res = requests.get(url, headers = headers, timeout = timeout)
# 获取页面的响应状态码(200/404/301等)
http_status = res.status_code
# 获取待采集页面的编码(UTF-8,GBK等编码)
res_encoding = res.encoding
# 获得采集页面的HTML代码,转化为UTF8编码,避免乱码问题
html_code = res.text.encode(res.encoding).decode('utf8')
# 把HTML代码转化为用Beautiful Soup变成DOM对象,解析内核使用lxml,效率高
soup = bs(html_code, "lxml")
# 通过DOM标签拿到搜索结果标题部分代码块
for item in soup.select(".c-container h3.t"):
# 获取标题文本,strip()去掉前后空格
title = item.get_text().strip()
# 标题模块读第一个A标签对应的百度加密URL
encode_url = item.select('a')[0].get('href')
# 使用Request Head方法请求加密URL,从跳转后的Header信息中获得真实地址
true_url = requests.head(encode_url, allow_redirects=False).headers.get('location')
# 判断待查询的URL是否出现在百度搜索结果页面的真实URL中
if item_url in true_url:
# 如果包含,则说明已被百度收录
indexed = True
# 循环就可以退出
break
# 否则标记为未收录,继续循环
else:
indexed = False
# 返回收录与否的判断,True代表收录,False代表没收录。
return indexed
# 为测试,使用构造好的二维列表,每个值都是一个列表,包含标题和对应的网址。
# 实际使用中,可以采集网址列表数据,或直接从数据库中读取标题和网址。
need_check = [["百度","https://www.west.cn/services/vhostsoft/"], ["铠装热电偶-安徽华光仪表线缆公司生产", "http://yiqiyibiao.huangye88.com/xinxi/91791764.html"]]
# 循环判断页面是否已被百度收录
for i in need_check:
# 待查询的标题
title = i[0].strip()
# 待查询的网址
url = i[1].strip()
# 根据标题和网站查询百度前三页的结果
rs = get(title, url)
# 如果返回True,则说明被收录,否则没收录。
if rs:
print("恭喜,百度已收录:{},网页标题:{}".format(url, title))
else:
print("抱歉,百度未收录:{},网页标题:{}".format(url, title))
# 把查询结果通过tab键分隔开写入文本文件中,便于以后用Excel分析
with open('check_result.txt', 'a') as f:
f.write(url + "\t" + str(rs) + "\t" + title + "\n")
#提示查询结果已写入文件中
print("查询结果已写入文件:check_result.txt")