【问题标题】:BeautifulSoup can't crawl google search results?BeautifulSoup 无法抓取 google 搜索结果?
【发布时间】:2015-07-10 05:41:36
【问题描述】:

试图爬取谷歌搜索结果。这段代码适用于所有其他网站,我已经尝试过,但不适用于谷歌。它返回一个空列表。

from BeautifulSoup import BeautifulSoup
import requests

def googlecrawler(search_term):
    url="https://www.google.co.in/?gfe_rd=cr&ei=UVSeVZazLozC8gfU3oD4DQ&gws_rd=ssl#q="+search_term
    junk_code=requests.get(url)
    ok_code=junk_code.text
    good_code=BeautifulSoup(ok_code)
    best_code=good_code.findAll('h3',{'class':'r'})
    print best_code


googlecrawler("healthkart") 

它应该返回类似这样的东西。

<h3 class="r"><a href="/url?  sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=6&amp;cad=rja&amp;uact=8&amp;ved=0CEIQFjAF&amp;url=http%3A%2F%2Fwww.coupondunia.in%2Fhealthkart&amp;ei=qFmfVc2fFNO0uASti4PwDQ&amp;usg=AFQjCNFHMzqn-rH4Hp-fZK0E4wwxJmevEg&amp;sig2=QgwxMBdbPndyQTSH10dV2Q" onmousedown="return rwt(this,'','','','6','AFQjCNFHMzqn-rH4Hp-fZK0E4wwxJmevEg','QgwxMBdbPndyQTSH10dV2Q','0CEIQFjAF','','',event)" data-href="http://www.coupondunia.in/healthkart">HealthKart Coupons: July 2015 Coupon Codes</a></h3>

【问题讨论】:

  • 抓取 Google 违反了他们的服务条款,他们保留设置技术障碍来执行这些条款的权利。因此,随着执行它的障碍得到改善,我们给您的任何答案都可能在相当短的时间内中断。如果您想以编程方式搜索 Google,请通过支持的 API 注册一个密钥。
  • 哦,好吧..只是为了好玩..明白..谢谢:)
  • @TusharBakaya 如果您使用 Chrome 或 Firefox 查看页面源代码,您应该会看到它实际上是作为 Javascript 返回的,然后组装到 HTML 客户端。我的猜测是您正在检查元素,这将向您显示 post-JS 结果。 BeautifulSoup 只是抓取原始的基于 JS 的源码。
  • 这完全有道理。知道该怎么做吗?

标签: python beautifulsoup web-crawler google-crawlers


【解决方案1】:

看着good_code,我根本看不到h3class "r"。这就是您的代码返回空列表的原因。

您的代码本身没有问题,而是您要搜索的内容不存在。

您期望返回什么?

【讨论】:

  • 这就是问题所在。正如 Matthew 所指出的,BS 只是在获取基于 JS 的原始源代码。
【解决方案2】:

一种常见的解决方案是添加user-agent 并将介绍请求headers 传递给虚假真实用户访问:

# https://www.whatismybrowser.com/guides/the-latest-user-agent/
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"
}

所以您的代码将如下所示:

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"
}

def googlecrawler(search_term): 
    html = requests.get(f'https://www.google.com/search?q=', headers=headers).text
    soup = BeautifulSoup(html, 'lxml')

    for container in soup.findAll('div', class_='tF2Cxc'):
        title = container.select_one('.DKV0Md').text
        link = container.find('a')['href']
        print(f'{title}\n{link}')

googlecrawler('site:Facebook.com Dentist gmail.com')

# part of the output:
'''
COVID-19 Office Update Dear... - Canton Dental Associates ...
https://www.facebook.com/permalink.php?id=107567882605441&story_fbid=3205134459515419

Spinelli Dental - General Dentist - Rochester, New York ...
https://www.facebook.com/spinellidental/about/?referrer=services_landing_page

LaboSmile USA Dentist & Dental Office in Delray ... - Facebook
https://www.facebook.com/labosmileusa/
'''

或者,您可以使用来自 SerpApi 的 Google Search Engine Results API 来完成此操作。这是一个带有免费计划的付费 API。

要集成的代码:

from serpapi import GoogleSearch
import os, json, re

params = {
  "engine": "google",
  "q": "site:Facebook.com Dentist gmail.com",
  "api_key": os.getenv('API_KEY')
}

search = GoogleSearch(params)
results = search.get_dict()

for result in results['organic_results']:
  title = result['title']
  link = result['link']
  print(f'{title}\n{link}\n')

# part of the output:
'''
Green Valley Dental - About | Facebook
https://www.facebook.com/GVDFamily/about/

My Rivertown Dentist - About | Facebook
https://www.facebook.com/Rivertownfamily/about/

COVID-19 Office Update Dear... - Canton Dental Associates ...
https://www.facebook.com/permalink.php?id=107567882605441&story_fbid=3205134459515419
'''

免责声明,我为 SerpApi 工作。

【讨论】:

    猜你喜欢
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 2020-06-19
    • 1970-01-01
    • 2021-06-28
    • 1970-01-01
    相关资源
    最近更新 更多