python - 抓取谷歌网络结果不起作用

标签 python python-3.x web-scraping beautifulsoup

为什么以下内容无法抓取 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/

相关文章:

python - 如何将字符串 ['2019-06-01T23:07:02.000+0000' ] 转换为 Python 3 中的日期时间对象

python - 在 Mac 上使用 Docker 使用 Py2exe

python - 我如何设置 Scrapy 来处理验证码

ms-access - 从网站上的表格中抓取数据,而无需搜索标签

python - 如何获取 anchor 标签内的元素?

python - python 中的元组与列表对象

python - 在 pyjade 中使用 python 代码

Python 跟踪模块和文件路径

python - 使用列表替换字符串中的子字符串

python - 使用 python : KeyError: 'O' 解析文件时出现逻辑错误