python 必应搜索教程

必应搜索:
使用库:requests;bs4
目标:

  • 分析必应的url
  • 获取信息,解析为BeautifulSoup对象
  • 提取信息,输出信息
  • 源代码放在最后

1.分析URL:

https://cn.bing.com/search?#搜索URL
q=000#搜索内容
form=ANNTH1#国内版ANNTH1、国际版BESBTB
......#其余参数为特殊的验证码,不影响结果

建立 类 bi:

import requests
from bs4 import BeautifulSoup
class bi:
    def make_url(self,q):
        return 'https://cn.bing.com/search?q=' + q

2.获取信息:
右键检查,我们发现所有信息都位于第一个’ol’标签中。
必应HTTPS的架构

class bi:
    def find(self):
        u = self.make_url(q)#构造URL
        r = requests.get(u)#发送GET请求获取信息
        soup = BeautifulSoup(r.text, 'html5lib')
        #用BeautifulSoup,html5lib进行解析,html5lib需要下载(不需要导入)
        #pip install html5lib
        all_ = soup.find('ol')#第一个<ol>
        a=all_.find_all('li')#<ol>下所有<li>存储到列表
        return a

3.提取信息:
循环列表提取信息
li架构
li架构

介绍
介绍文本
标题
标题文本

class bi:
    def get(self,q):
        a=self.find()
        things = []
        for tag in a:
            try:
                item1 = tag.find(class_='b_title')
                url = item1.find('h2').find('a')['href']
                #页面的网址
                icon = item1.find('a').find('img')['src']
                # 页面的图标
                title = item1.text#只需要其中的文本内容
                item2=tag.find(class_='b_caption')
                text=item2.find('p').text
                #介绍内容
                thing = {'title': title, 'url': url, 'text':text, icon: 'icon'}
                #把信息存入字典
                things.append(thing)
                #把字典加入列表
            except:
                pass
                #有的信息架构特殊,使程序不报错
        return things

4.old源代码:

import requests
from bs4 import BeautifulSoup
class bi:
    def make_url(self,q):
        return 'https://cn.bing.com/search?q=' + q
    def find(self):
        u = self.make_url(q)#构造URL
        r = requests.get(u)#发送GET请求获取信息
        soup = BeautifulSoup(r.text, 'html5lib')
        #用BeautifulSoup,html5lib进行解析,html5lib需要下载(不需要导入)
        #pip install html5lib
        all_ = soup.find('ol')#第一个<ol>
        a=all_.find_all('li')#<ol>下所有<li>存储到列表
        return a
    def get(self,q):
        a=self.find()
        things = []
        for tag in a:
            try:
                item1 = tag.find(class_='b_title')
                url = item1.find('h2').find('a')['href']
                #页面的网址
                icon = item1.find('a').find('img')['src']
                # 页面的图标
                title = item1.text#只需要其中的文本内容
                item2=tag.find(class_='b_caption')
                text=item2.find('p').text
                #介绍内容
                thing = {'title': title, 'url': url, 'text':text, icon: 'icon'}
                #把信息存入字典
                things.append(thing)
                #把字典加入列表
            except:
                pass
                #有的信息架构特殊,使程序不报错
        return things

if __name__=='__main__':
    n=bi()
    a=input('Bing\n必应搜索:')
    for i in n.get(a):
        print(i['title'])
        print(i['url'])
        print(i['text'])
        print('_'*100+'\n')

5.new源代码

import requests
from bs4 import BeautifulSoup
class bing:
    def __init__(self):
        '''
        bing请求类
        
        Dict:
        header
        
        Function:
        __init__(self)
        make_url(self,q,data='chinese',pagenum='1')
        jx(self,url)

        Returns
        -------
        None.

        '''
        self.header = {
            'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36 Edg/108.0.1462.76'
            }


    def make_url(self,q,data='chinese',pagenum='1'):
        '''
        生成必应url
        
        Parameters
        ----------
        q : str
            关键字
            data : str, optional
            'chinese' or 'english'. The default is 'chinese'.
            pagenum : str, optional
            The default is '1'.
            
            Returns
            -------
            url.

        '''
        if data != 'chinese' and data != 'english':
            assert data != 'chinese' and data != 'english', '不支持中英文以外的文字'
    
        if data == 'chinese':
            urls = 'https://cn.bing.com/search?q='+q+'&form=ANSPH1'
        elif data == 'english':
            urls = 'https://cn.bing.com/search?q='+q+'&FORM=BESBTB&ensearch=1'
                
        if pagenum == '1':
            return urls
        r = requests.get(urls,headers = self.header)
        s = BeautifulSoup(r.text,'html5lib')
        page = s.find('li',class_ = 'b_pag')
        pages = page.find_all('li')
        pageurls = {}
        for i in pages:
            try:
                pageurls[i.text] = i.find('a')['href']
            except:
                pass
    
        try:
            return pageurls[pagenum]
        except:
            return urls
    
    

    def jx(self,url):
        '''
        请求并解析url

        Parameters
        ----------
        url : str
            usually from function make_url.

        Returns
        -------
        None.

        '''
        r = requests.get(url,headers = self.header)
        s = BeautifulSoup(r.text,'html5lib')
        lis = s.find_all('li',class_ = 'b_algo')
        rlist = []
        # data = {'title':'','js':'','url':'','icon_url':''}
        
        for i in lis:
            data = {}
            
            data['title'] = i.find('div',class_ = 'b_title').find('h2').text
            data['url'] = i.find('div',class_ = 'b_title').find('h2').find('a')['href']
            try:
                data['js'] = i.find('p').text # .find('div',class_ = 'b_caption')
            except:
                data['js'] = 'no js'
                
            try:
                data['icon_url'] = i.find('div',class_ = 'b_title').find('a').find('div',class_ = 'rms_iac')['data-src']
            except:
                data['icon_url'] = 'no icon'
            rlist.append(data)
        return rlist
    
if __name__ == '__main__':         
    k = bing()
    url = k.make_url('bs4')
    rlist = k.jx(url)
    for i in rlist:
        for j in i:
            print(i[j])
        print('\n')
  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要使用Python 3来批量下载Bing搜索的图片,可以按照以下步骤进行: 1. 首先,需要安装requests和beautifulsoup4这两个库。可以使用以下命令安装它们: ``` pip install requests pip install beautifulsoup4 ``` 2. 导入所需的模块: ```python import requests from bs4 import BeautifulSoup import os ``` 3. 创建一个函数来下载图片: ```python def download_image(url, save_dir): filename = os.path.join(save_dir, url.split('/')[-1]) response = requests.get(url, stream=True) if response.status_code == 200: with open(filename, 'wb') as file: file.write(response.content) print('成功下载图片:', filename) else: print('无法下载图片:', url) ``` 4. 定义一个函数来搜索并批量下载图片: ```python def download_images(query, save_dir, num_images): search_url = 'https://www.bing.com/images/search?q=' + query response = requests.get(search_url) if response.status_code == 200: soup = BeautifulSoup(response.text, 'html.parser') image_tags = soup.find_all('img') count = 0 for image_tag in image_tags: image_url = image_tag['src'] if image_url.startswith('https://'): download_image(image_url, save_dir) count += 1 if count == num_images: break else: print('搜索失败') ``` 5. 调用download_images函数并指定搜索的关键字、保存目录以及要下载的图片数量: ```python query = '美食' # 搜索关键字 save_dir = 'images' # 图片保存目录 num_images = 10 # 要下载的图片数量 download_images(query, save_dir, num_images) ``` 运行脚本后,将会在指定目录下下载指定数量的Bing搜索结果的图片。 需要注意的是,根据Bing的使用条款,禁止使用非官方API进行批量下载图片。因此,在使用此方式之前,请确保你已阅读并遵守相关使用条款。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值