1048. Find Coins (25)

本文介绍了一个C++程序,用于从给定的整数数组中找到两个数,它们的和等于指定的目标值M。通过使用标准库函数进行排序,并利用upper_bound函数定位可能的配对,实现了高效的查找算法。
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>

#include <string>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

int a[100005]={0};

int main()
{
  //  freopen("in.txt","r",stdin);

    int N,M;
    scanf("%d %d",&N,&M);

    for(int i=1;i<=N;i++)
    {
        scanf("%d",&a[i]);
    }

    sort(a+1,a+1+N);

    int p;
    int i;
    for(i=1;i<=N;i++)
    {                    // a[i+1]~a[N]中第一个超过M-a[i]的数
        p=upper_bound(a+i+1,a+N+1,M-a[i])-a;
        if(a[p-1]+a[i]==M && p-1!=i)//p-1!=i表示不能是同一个数用两次
        {
            printf("%d %d\n",a[i],a[p-1]);
            break;
        }
    }

    if(i==N+1)
        printf("No Solution");

    //for(int i=0;i<=N;i++)
      //  printf("%d ",a[i]);







    return 0;
}


from bs4 import BeautifulSoup import requests import lxml import openpyxl import os def get_html(url,headers,data): try: response = requests.get(url, headers=headers, params=data) if response.status_code == 200: return response.text else: print('请求失败') except Exception as e: print(e) def save_data(html): soup=BeautifulSoup(html,'lxml') node=soup.find_all('table') for sub_node in node: title=sub_node.find_all('h1')[2].get('title') likes=sub_node.find_all('span',{'class':'video-like-info video-toolbar-item-text'})[0].string coins=sub_node.find_all('span',{'class':'video-coin-info video-toolbar-item-text'})[0].string favorites=sub_node.find_all('span',{'class':'video-fav-info video-toolbar-item-text'})[0].string shares=sub_node.find_all('span',{'class':'video-share-info video-toolbar-item-text'})[0].string description=sub_node.find_all('span',{'class':'desc-info-text'})[0].string print(title, likes, coins, favorites, shares, description) sheet.append([title, likes, coins, favorites, shares, description]) if __name__ == "__main__": path='d:\\video' if not os.path.exists(path): os.mkdir(path) os.chdir(path) wb = openpyxl.Workbook() sheet = wb.active sheet.append(['标题', '点赞人数', '投币人数', '收藏人数', '转发人数','视频介绍']) url ='https://search.bilibili.com/all?vt=68706038&keyword=python&page=''' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36' } data={ 'page':0 } for page in range(0,11): data['page'] = page html = get_html(url,headers,data) save_data(html) wb.save('video.xlsx') 请将我的代码完善,我想要实现前十页视频爬取的相关内容
最新发布
06-13
你的代码存在一些问题,例如`find_all('h1')[2]`可能会导致索引错误,因为并不是所有的`table`标签下都有足够的`h1`标签。此外,B站的搜索结果页面结构可能与你的代码假设不一致,因此需要仔细分析HTML结构。 以下是完善后的代码,并且对可能的问题进行了修正: ```python from bs4 import BeautifulSoup import requests import openpyxl import os def get_html(url, headers, params): try: response = requests.get(url, headers=headers, params=params) if response.status_code == 200: return response.text else: print(f'请求失败,状态码:{response.status_code}') except Exception as e: print(f'请求出错:{e}') def save_data(html, sheet): soup = BeautifulSoup(html, 'lxml') # 查找所有视频信息的容器 video_containers = soup.find_all('li', class_='video-item matrix') for container in video_containers: try: title = container.find('a', class_='title').get('title') # 视频标题 likes = container.find('span', class_='data-box').text.strip() if container.find('span', class_='data-box') else 'N/A' # 点赞人数 coins = container.find('span', class_='coin').text.strip() if container.find('span', class_='coin') else 'N/A' # 投币人数 favorites = container.find('span', class_='collect').text.strip() if container.find('span', class_='collect') else 'N/A' # 收藏人数 shares = container.find('span', class_='share').text.strip() if container.find('span', class_='share') else 'N/A' # 转发人数 description = container.find('span', class_='des').text.strip() if container.find('span', class_='des') else 'N/A' # 视频介绍 print(title, likes, coins, favorites, shares, description) sheet.append([title, likes, coins, favorites, shares, description]) except Exception as e: print(f'解析数据时出错:{e}') if __name__ == "__main__": path = 'd:\\video' if not os.path.exists(path): os.mkdir(path) os.chdir(path) wb = openpyxl.Workbook() sheet = wb.active sheet.append(['标题', '点赞人数', '投币人数', '收藏人数', '转发人数', '视频介绍']) base_url = 'https://search.bilibili.com/all?keyword=python&page=' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36' } for page in range(1, 11): # 爬取前10页 url = f'{base_url}{page}' html = get_html(url, headers, None) if html: save_data(html, sheet) wb.save('video.xlsx') print("数据已保存到 video.xlsx") ``` ### 解释代码: 1. **`get_html`函数**: - 该函数用于发送HTTP请求并获取网页内容。 - 如果请求成功(状态码为200),返回HTML文本;否则打印错误信息。 2. **`save_data`函数**: - 使用BeautifulSoup解析HTML,提取视频的相关信息。 - 遍历每个视频容器(`li.video-item.matrix`),提取标题、点赞数、投币数、收藏数、转发数和描述。 - 如果某些字段不存在,则使用默认值`N/A`。 3. **主程序部分**: - 创建一个Excel文件并定义表头。 - 循环爬取前10页的数据。 - 将提取的数据写入Excel文件。 --- ### 注意事项: 1. **反爬机制**: - B站可能有反爬机制,频繁请求可能会导致IP被封禁。可以考虑加入随机延时或使用代理池。 2. **HTML结构变化**: - 网站的HTML结构可能会随时间变化,因此需要定期检查并调整代码。 3. **异常处理**: - 在解析HTML时,添加了异常处理以避免因缺失字段导致程序崩溃。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值