如何在Google自定义搜索API中获取网站的完整标题?

问题描述 投票:0回答:1

这是我的代码。

def google_search(query, **kwargs):
    service = build("customsearch", "v1", developerKey=app.config.get("GOOGLE_API_KEY"))
    res = service.cse().list(q=query, cx=app.config.get("GOOGLE_CSE_KEY"),**kwargs).execute()
    return res['items']

response = google_search(query, num=pageSize, start=start)
for item in response:
    print('Title: ', item['title'])

结果如下:

正如您在屏幕截图中看到的,其中一个标题以“...”结尾。省略了。 但我想从结果中获得完整的标题。

我尝试使用硒获得完整标题。但需要很长时间。

def get_full_title(title, url):
    if title.endswith("..."):
        driver = webdriver.Chrome(options=options)
        driver.get(url)
        fullTitle = driver.title
        driver.quit()
        return fullTitle
    return title

所以我想,硒不是解决方案。

如何获得完整头衔? 是否有任何设置可以在可编程搜索引擎中获取完整标题?

python google-api-python-client google-custom-search page-title
1个回答
0
投票

如果您在项目列表中有可用的 URL,您可以使用

requests
bs4
(BeautifulSoup) 快速获取标题:

安装要求:

pip install requests
pip install bs4

代码:

import requests
from bs4 import BeautifulSoup


def get_page_title(url: str) -> str:
  response = requests.get(url)
  soup = BeautifulSoup(response.content, features="html.parser")
  return soup.title.string


url = "https://stackoverflow.com/questions/77901995/how-to-get-full-title-of-website-in-google-custom-search-api"

title = get_page_title(url)

print(title)

运行当前 SO 页面会返回

python - How to get full title of website in google custom search api? - Stack Overflow
(无省略号)。

© www.soinside.com 2019 - 2024. All rights reserved.