这是我的代码。
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
所以我想,硒不是解决方案。
如何获得完整头衔? 是否有任何设置可以在可编程搜索引擎中获取完整标题?
如果您在项目列表中有可用的 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
(无省略号)。