如何使用Python请求检索10个首个Google搜索结果
我看到了很多关于这个主题的问题,我发现谷歌一直在更新其搜索引擎API的工作方式 这个链接>正好显示了我需要什么,但问题是我不知道是否有可能再这样做了 我的学期论文需要这个,但通过阅读谷歌文档,我找不到一个方法来做到这一点。如何使用Python请求检索10个首个Google搜索结果,python,google-api,urllib,google-search-api,Python,Google Api,Urllib,Google Search Api,我看到了很多关于这个主题的问题,我发现谷歌一直在更新其搜索引擎API的工作方式 这个链接>正好显示了我需要什么,但问题是我不知道是否有可能再这样做了 我的学期论文需要这个,但通过阅读谷歌文档,我找不到一个方法来做到这一点。 我已经完成了“入门”的工作,我得到的只是一个使用自定义搜索引擎(CSE)的私人搜索引擎。或者,你可以使用Python、Selenium和PhantomJS或其他浏览器浏览谷歌的搜索结果并获取内容。我个人没有这样做过,也不知道那里是否有挑战 我相信最好的方法是使用他们的搜索AP
我已经完成了“入门”的工作,我得到的只是一个使用自定义搜索引擎(CSE)的私人搜索引擎。或者,你可以使用Python、Selenium和PhantomJS或其他浏览器浏览谷歌的搜索结果并获取内容。我个人没有这样做过,也不知道那里是否有挑战
我相信最好的方法是使用他们的搜索API。请试试你指出的那个。如果它不起作用,寻找新的API 我在自己解决这个问题时遇到了这个问题,我找到了一个更新的解决方案 基本上,我使用这个指南来生成我自己的api密钥和搜索引擎,然后使用python请求来检索json结果
def search(query):
api_key = 'MYAPIKEY'
search_engine_id = 'MYENGINEID'
url = "https://www.googleapis.com/customsearch/v1/siterestrict?key=%s&cx=%s&q=%s" % (api_key, search_engine_id, query)
result = requests.Session().get(url)
json = simplejson.loads(result.content)
return json
我通过链接回答了您附加的问题 下面是答案和答案的答案。我将复制代码以便更快地访问
第一种方法是使用返回JSON的自定义脚本:
from bs4 import BeautifulSoup
import requests
import json
headers = {
'User-agent':
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
html = requests.get('https://www.google.com/search?q=java&oq=java',
headers=headers).text
soup = BeautifulSoup(html, 'lxml')
summary = []
for container in soup.findAll('div', class_='tF2Cxc'):
heading = container.find('h3', class_='LC20lb DKV0Md').text
article_summary = container.find('span', class_='aCOpRe').text
link = container.find('a')['href']
summary.append({
'Heading': heading,
'Article Summary': article_summary,
'Link': link,
})
print(json.dumps(summary, indent=2, ensure_ascii=False))
使用来自SerpApi的:
import os
from serpapi import GoogleSearch
params = {
"engine": "google",
"q": "java",
"api_key": os.getenv("API_KEY"),
}
search = GoogleSearch(params)
results = search.get_dict()
for result in results["organic_results"]:
print(f"Title: {result['title']}\nLink: {result['link']}\n")
免责声明,我为SerpApi工作
谢谢你的回答,我将看看selenium并尝试使用Yahoo!在最坏的情况下。如果答案对你有帮助,你可以投票并接受它。已经投票,只是不接受,因为它实际上没有解决问题,投票不能被看到,因为我还没有15分,但我拥有它