我正在使用 python 中的请求库从谷歌结果中GET
数据。 https://www.google.com.pk/#q=pizza&num=10正如我提到的num=10
,将返回 google 的前 10 个结果。最终https://www.google.com.pk/#q=pizza&num=100将返回 100 个 google 结果。
但是
如果我写任何超过 100 的数字,让 https://www.google.com.pk/#q=pizza&num=200 , google 仍然返回前 100 个结果
如何一次获得超过 100 个?
代码:
import requests
url = 'http://www.google.com/search'
my_headers = { 'User-agent' : 'Mozilla/11.0' }
payload = { 'q' : pizza, 'start' : '0', 'num' : 200 }
r = requests.get( url, params = payload, headers = my_headers )
在“r”中,我仅获得 google 前 100 个结果的 URL,而不是 200
最佳答案
您可以使用来自 google 的更具编程性的 api 来获取结果,而不是尝试屏幕抓取人类搜索界面,没有错误检查或断言这符合所有 google 条款和条件,建议您查看使用此的详细信息网址:
import requests
def search(query, pages=4, rsz=8):
url = 'https://ajax.googleapis.com/ajax/services/search/web'
params = {
'v': 1.0, # Version
'q': query, # Query string
'rsz': rsz, # Result set size - max 8
}
for s in range(0, pages*rsz+1, rsz):
params['start'] = s
r = requests.get(url, params=params)
for result in r.json()['responseData']['results']:
yield result
例如获取“google”的 200 个结果:
>>> list(search('google', pages=24, rsz=8))
[{'GsearchResultClass': 'GwebSearch',
'cacheUrl': 'http://www.google.com/search?q=cache:y14FcUQOGl4J:www.google.com',
'content': 'Search the world's information, including webpages, images, videos and more. \n<b>Google</b> has many special features to help you find exactly what you're looking\xa0...',
'title': '<b>Google</b>',
'titleNoFormatting': 'Google',
'unescapedUrl': 'https://www.google.com/',
'url': 'https://www.google.com/',
'visibleUrl': 'www.google.com'},
...
]
要使用 Google 的自定义搜索 API,您需要注册为开发者。您每天可以获得 100 个免费查询(我不确定这是 API 调用还是允许对同一查询进行分页算作 1 个查询):
- 注册@ https://console.developers.google.com
- 创建项目
- 创建
key
- 启用自定义搜索 API
- 创建自定义搜索引擎 @ https://cse.google.com
- 使用虚拟站点初始化 CSE
- 编辑 CSE 以搜索整个网络
- 删除虚拟网站
- 获取 CSE 引用(查看
cx=<cse reference>
的公共(public)网址)
您可以使用requests
进行查询:
import requests
url = 'https://www.googleapis.com/customsearch/v1'
params = {
'key': '<key>',
'cx': '<cse reference>',
'q': '<search>',
'num': 10,
'start': 1
}
resp = requests.get(url, params=params)
results = resp.json()['items']
与 start
您可以进行与上面类似的分页。
还有许多其他可用参数,您可以查看 CSE 的 REST 文档:https://developers.google.com/custom-search/json-api/v1/reference/cse/list#request
Google 还有一个客户端 API 库:pip install google-api-python-client
您还可以使用:
from googleapiclient import discovery
service = discovery.build('customsearch', 'v1', developerKey='<key>')
params = {
'q': '<query>',
'cx': '<cse reference>',
'num': 10,
'start': 1
}
query = service.cse().list(**params)
results = query.execute()['items']
关于python - 如何一次性抓取超过 100 个谷歌页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34614057/