无法使用硒从 Google 搜索结果中抓取整个页面

时间:2021-05-22 12:08:32

标签: selenium web-scraping

我正在尝试使用 selenium chromedriver 抓取 Google 结果。之前,我使用 requests + Beautifulsoup 来抓取 google 结果,这很有效,但是在大约 300 个结果后我被 Google 屏蔽了。我一直在阅读这个主题,在我看来,使用 selenium + webdriver 不太容易被 Google 阻止。

现在,我正在尝试使用 selenium 抓取 Google 结果。我想抓取所有项目的标题、链接和描述。本质上,我想这样做:How to scrape all results from Google search results pages (Python/Selenium ChromeDriver)

<块引用>

NoSuchElementException:没有这样的元素:无法定位元素: {"method":"css selector","selector":"h3"}(会话信息: 铬=90.0.4430.212)

因此,我正在尝试另一个代码。此代码能够抓取一些,但不是所有的标题 + 描述。见下图。我无法抓取最后 4 个标题,最后 5 个描述也是空的。这有什么线索吗?非常感谢。

import urllib
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

root = "https://www.google.com/"
url = "https://google.com/search?q="

query = 'Why do I only see the first 4 results?'  # Fill in google query
query = urllib.parse.quote_plus(query)
link = url + query

print(f'Main link to search for: {link}')

options = Options()
# options.headless = True
options.add_argument("--window-size=1920,1200")
driver = webdriver.Chrome(options=options)
driver.get(link)

wait = WebDriverWait(driver, 30)
wait.until(EC.presence_of_all_elements_located((By.XPATH, './/h3')))

link_tag    = './/div[@class= "yuRUbf"]/a'
title_tag   = './/h3'
description_tag = './/span[@class= "aCOpRe"]'


titles = driver.find_elements_by_xpath(title_tag)
links = driver.find_elements_by_xpath(link_tag)
descriptions = driver.find_elements_by_xpath(description_tag)

for t in titles:
    print('title:', t.text)
for l in links:
    print('links:', l.get_attribute("href"))
for d in descriptions:
    print('descriptions:', d.text)    

# Why are the last 4 titles and the last 5 descriptions empty??

结果图片:enter image description here

1 个答案:

答案 0 :(得分:0)

因为这 4 个不是实际链接,Google 总是显示“人们也问”。如果你看到他们的 DOM 结构

<div style="padding-right:24px" jsname="xXq91c" class="cbphWd" data-
kt="KjCl66uM1I_i7PsBqYb-irfI74DmAeDWm-uv7IveYLKIxo-bn9L1H56X2ZSUy9L-6wE" 
data-hveid="CAgQAw" data-ved="2ahUKEwjAoJ2ivd3wAhXU-nMBHWj1D8EQuk4oAHoECAgQAw">
How do I get Google to show all results?
</div>

它不是锚标记,因此您不会看到 href 标记,因此您的链接列表将有 4 个空值,因为有 4 个类似的 div。

要获取这 4 个,您需要使用不同的定位器:

XPATH://*[local-name()='svg']/../following-sibling::div[@style]

title_tags = driver.find_elements(By.XPATH, "//*[local-name()='svg']/../following-sibling::div[@style]")
for title in title_tags:
   print(title.text)