You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

baidu.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import random
  17. from abc import ABC
  18. from functools import partial
  19. import pandas as pd
  20. import requests
  21. import re
  22. from agent.settings import DEBUG
  23. from agent.component.base import ComponentBase, ComponentParamBase
  24. class BaiduParam(ComponentParamBase):
  25. """
  26. Define the Baidu component parameters.
  27. """
  28. def __init__(self):
  29. super().__init__()
  30. self.top_n = 10
  31. def check(self):
  32. self.check_positive_integer(self.top_n, "Top N")
  33. class Baidu(ComponentBase, ABC):
  34. component_name = "Baidu"
  35. def _run(self, history, **kwargs):
  36. ans = self.get_input()
  37. ans = " - ".join(ans["content"]) if "content" in ans else ""
  38. if not ans:
  39. return Baidu.be_output("")
  40. try:
  41. url = 'https://www.baidu.com/s?wd=' + ans + '&rn=' + str(self._param.top_n)
  42. headers = {
  43. 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36'}
  44. response = requests.get(url=url, headers=headers)
  45. url_res = re.findall(r"'url': \\\"(.*?)\\\"}", response.text)
  46. title_res = re.findall(r"'title': \\\"(.*?)\\\",\\n", response.text)
  47. body_res = re.findall(r"\"contentText\":\"(.*?)\"", response.text)
  48. baidu_res = [{"content": re.sub('<em>|</em>', '', '<a href="' + url + '">' + title + '</a> ' + body)} for
  49. url, title, body in zip(url_res, title_res, body_res)]
  50. del body_res, url_res, title_res
  51. except Exception as e:
  52. return Baidu.be_output("**ERROR**: " + str(e))
  53. if not baidu_res:
  54. return Baidu.be_output("")
  55. df = pd.DataFrame(baidu_res)
  56. if DEBUG: print(df, ":::::::::::::::::::::::::::::::::")
  57. return df