为什么以下内容无法抓取 Google 的搜索结果?
尝试打开响应失败并抛出 HTTPError
。我查看了其他问题,据我所知,我已经正确完成了编码等。
我知道我没有包含捕获错误等,这只是一个缩小版本。
def scrape_google(query):
url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
headers = {'User-Agent': 'Mozilla/5.0'}
search = urllib.parse.urlencode({'q': " ".join(term for term in query)})
b_search = search.encode("utf-8")
response = urllib.request.Request(url, b_search, headers)
page = urllib.request.urlopen(response)
最佳答案
它不起作用,因为该 URL 的返回是 JSON 格式。如果您使用该 URL 并输入如下搜索词:
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=bingo
您将以 JSON 格式返回结果,这不是 beautifulsoup 处理的内容。 (但它比抓取要好得多)
{"responseData":
{"results":
[{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://www.pogo.com/games/bingo-luau","url":"http://www.pogo.com/games/bingo-
//etc
编辑添加:
使用请求:
url = ('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=bingo')
resp = requests.get(url)
print(resp.content)
生成:
b'{"responseData": {"results":[{"GsearchResultClass":"GwebSearch","unescapedUrl":"http://www.pogo.com/games/b...
//etc
关于python - 抓取谷歌网络结果不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34098995/