无法使用漂亮的汤刮Google搜索结果

时间:2019-05-10 11:57:26

标签: python-3.x beautifulsoup

我正在尝试从Google搜索结果中抓取产品的flipkart链接。但是,当我尝试通过将链接与文本“ flipkart”进行匹配来打印链接时,它不会打印任何内容。我究竟做错了什么?

这是html结构的一部分:

<div class="r">
<a href="https://www.flipkart.com/redmi-note-7-pro-nebula-red-64- 
gb/p/itmferghuf9ky6ru" ping="/url?=https://www.flipkart.com/redmi- 
note-7-pro-nebula-red-64-gb/p/itmferghuf9ky6ru&amp"> 

查询结果位于div class =“ r”下。从那个div我试图获取锚标记链接。

这是我的代码

input='note 7 pro'
urllib.parse.quote_plus(input)

html = getHTML('https://www.google.co.in/search?q='+input)
main_div=html.findAll('div', {'class':'r'})

for div in main_div:
    link = div.find('a')[href]
    if 'flipkart' in link:
        print(link)

输出应为产品的完整flipkart链接。但是该程序未显示任何输出。

2 个答案:

答案 0 :(得分:0)

您肯定会在几个请求中得到Google的验证码。无论如何,我试图抓取一个Google页面,而div上的课程是g

但是您正在搜索的链接位于h3类的r中。

所以我认为您只需更改

main_div=html.findAll('div', {'class':'r'})

作者

main_div=html.findAll('h3', {'class':'r'})

目前应该可以正常工作

答案 1 :(得分:0)

要抓取 Flipkart 链接,您可以使用 select_one() bs4 方法执行以下操作:

soup.select_one('CSS_SELECTOR')

online IDE 中的代码和示例:

import requests, lxml
from bs4 import BeautifulSoup

headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3538.102 Safari/537.36 Edge/18.19582"
}

params = {'q': 'flipkart redmi note 10'}
html = requests.get('https://www.google.com/search', headers=headers, params=params).text
soup = BeautifulSoup(html, 'lxml')

filpkart_link = soup.select_one('.yuRUbf').a['href']
print(filpkart_link)

# output:
'''
https://www.flipkart.com/redmi-note-10-frost-white-64-gb/p/itm23973bd36fd21
'''

或者,您可以使用来自 SerpApi 的 Google Search Engine Results API 实现相同的目的。这是一个付费 API,可免费试用 5,000 次搜索。

基本上,主要区别在于一切都已经为最终用户完成,您不必弄清楚如何使解析器工作,例如维护解析器。

要集成的代码:

from serpapi import GoogleSearch
import os

params = {
  "api_key": os.getenv("API_KEY"),
  "engine": "google",
  "q": "flipkart redmi note 10",
}

search = GoogleSearch(params)
results = search.get_dict()
# [0] - index of the first results from Google Search Results
flipkart_link = results['organic_results'][0]['link']
print(flipkart_link)
# output:
'''
https://www.flipkart.com/redmi-note-10-frost-white-64-gb/p/itm23973bd36fd21
'''
<块引用>

免责声明,我为 SerpApi 工作。