【发布时间】:2020-09-03 09:19:45
【问题描述】:
我的问题
大家好
我正在尝试使用 Google API 和 Python 中的 Beautiful Soup 开发我的第一个网络爬虫。
目的是让爬虫询问用户输入,进行正常的 Google 搜索并以格式良好的方式返回许多结果。
我当前的代码成功检索数据,但它只返回 1 个结果。当我尝试对结果进行循环时,只会一遍又一遍地给我同样的结果。
我真正想要的是让脚本迭代不同的结果,例如Google 搜索结果的第一页并返回所有这些结果。我对编码很陌生,我猜它是在我的循环中的某个地方我犯了错误,但我想它也可能是 API 中的东西?
我非常感谢这里的一些帮助。此外,代码的格式可能很糟糕,请随时批评它,以便我可以更好地编写漂亮的代码:D
当前代码是
import sys
import urllib.request
import urllib.parse
import re
from urllib.request import urlopen as ureqs
from bs4 import BeautifulSoup as soup
from googleapiclient.discovery import build
# Google Personal Search Engine information
my_api_key = <key>
my_cse_id = <id>
# Google Search
def google_search(search_term, api_key, cse_id, **kwargs):
service = build('customsearch', 'v1', developerKey=api_key)
res = service.cse().list(q=search_term, cx=cse_id, **kwargs).execute()
return res
# Setting up so that user can input query
query = input("enter the query\n")
# Getting into printing the results
results = google_search(query, my_api_key, my_cse_id)
print("\n*********Google Search Results*********\n")
for i in results:
print("Title == " +results['items'][0]['title'])
print("Link ==" +results['items'][0]['link'])
snippet = results['items'][0]['snippet'].replace('\n', "")
html_snippet = results['items'][0]['htmlSnippet'].replace('\n', "")
html_snippet = html_snippet.replace("<b>", "")
html_snippet = html_snippet.replace("</b>", "")
html_snippet = html_snippet.replace("<br>", "")
html_snippet = html_snippet.replace(" …", ".")
print("Description == " + snippet+html_snippet)
【问题讨论】:
标签: python web-scraping beautifulsoup google-api