import requests
import re
from prompt_toolkit import print_formatted_text,HTML
from prompt_toolkit.styles import Style
# 设置文字颜色
style = Style.from_dict({
'aaa': '#FFFFFF',
'bbb': '#44ff00 italic',
'ttt': '#0000FF'
})
# 正则提取摘要和链接
title_pattern = re.compile('<a.target=..blank..target..(.*?)</a>')
brief_pattern = re.compile('K=.SERP(.*?)</p>')
#link_pattern = re.compile("(?<=(<cite>))(.*?)(?=</cite>)")
link_pattern = re.compile('(?<=(a.target=._blank..target=._blank..href=.))(.*?)(?=(..h=))')
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.61 Safari/537.36 Edg/94.0.992.31'}
# 要搜索多个关键词用+分隔
keyword = input("What you want to search? ")
page = 0
count = -10
while count < 0:
url = 'https://cn.bing.com/search?q={}&first={}'.format(keyword,page)
res = requests.get(url,headers=headers)
r = res.text
title = title_pattern.findall(r)
brief = brief_pattern.findall(r)
link = link_pattern.findall(r)
# 数据清洗
clear_brief = []
for i in brief:
tmp = re.sub('<[^<]+?>', '', i).replace('\n', '').strip()
tmp1 = re.sub('^.* ','', tmp).replace('\n', '').strip()
tmp2 = re.sub('^.*>','',tmp1).replace('\n','').strip()
clear_brief.append(tmp2)
clear_title = []
for i in title:
tmp = re.sub('^.*?>','', i).replace('\n', '').strip()
tmp2 = re.sub('<[^<]+?>', '', tmp).replace('\n', '').strip()
clear_title.append(tmp2)
#output
for i in range(len(brief)):
print_formatted_text(HTML('<ttt>{}</ttt>'.format(clear_title[i])),style=style)
print_formatted_text(HTML('<aaa>{}</aaa>'.format(clear_brief[i])),style=style)
print_formatted_text(HTML('<bbb>{}</bbb>'.format(link[i][1])),style=style)
print("============================================")
print(" ")
page += 10
count += -10
N = input("Do you want next page ENTER [y] or [n]? ")
if N == 'n':
break
用requests在命令行中实现bing搜索
最新推荐文章于 2024-09-04 15:53:15 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)