Hướng dẫn how to scrape data from google search using python - cách lấy dữ liệu từ tìm kiếm của google bằng cách sử dụng python

Bạn có 2 tùy chọn. Xây dựng nó hoặc sử dụng API SERP.

API SERP sẽ trả về kết quả tìm kiếm của Google dưới dạng phản hồi JSON được định dạng.

Tôi muốn giới thiệu API SERP vì nó dễ sử dụng hơn và bạn không phải lo lắng về việc bị chặn bởi Google.

1. API SERP

Tôi có kinh nghiệm tốt với API serp cạp.

Bạn có thể sử dụng mã sau để gọi API. Đảm bảo thay thế

import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
3 bằng mã thông báo API của hộp Scraperbox của bạn.

import urllib.parse
import urllib.request
import ssl
import json
ssl._create_default_https_context = ssl._create_unverified_context

# Urlencode the query string
q = urllib.parse.quote_plus("Where can I get the best coffee")

# Create the query URL.
query = "https://api.scraperbox.com/google"
query += "?token=%s" % "YOUR_API_TOKEN"
query += "&q=%s" % q
query += "&proxy_location=gb"

# Call the API.
request = urllib.request.Request(query)

raw_response = urllib.request.urlopen(request).read()
raw_json = raw_response.decode("utf-8")
response = json.loads(raw_json)

# Print the first result title
print(response["organic_results"][0]["title"])

2. Xây dựng cái cào Python của riêng bạn

Gần đây tôi đã viết một bài đăng trên blog chuyên sâu về cách cạo kết quả tìm kiếm với Python.

Đây là một bản tóm tắt nhanh chóng.

Đầu tiên, bạn nên nhận nội dung HTML của trang kết quả tìm kiếm Google.

import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")

Sau đó, bạn có thể sử dụng đẹp để trích xuất kết quả tìm kiếm. Ví dụ, mã sau đây sẽ nhận được tất cả các tiêu đề.

from bs4 import BeautifulSoup

# The code to get the html contents here.

soup = BeautifulSoup(html, 'html.parser')

# Find all the search result divs
divs = soup.select("#search div.g")
for div in divs:
    # Search for a h3 tag
    results = div.select("h3")

    # Check if we have found a result
    if (len(results) >= 1):

        # Print the title
        h3 = results[0]
        print(h3.get_text())

Bạn có thể mở rộng mã này để trích xuất các URL và mô tả kết quả tìm kiếm.

Mặc dù tôi nghi ngờ bạn có lẽ không được phép làm điều đó về mặt kỹ thuật, nhưng tôi nghi ngờ có một SEO ở vùng đất đã loại bỏ kết quả công cụ tìm kiếm của Google để phân tích chúng hoặc sử dụng một công cụ SEO làm điều tương tự. Nó rất thuận tiện hơn nhiều so với việc chọn qua các SERP để trích xuất các liên kết bằng tay.

Trong dự án này, tôi sẽ chỉ cho bạn cách bạn có thể xây dựng một máy cạo web tương đối mạnh mẽ (nhưng cũng hơi thiếu sót) bằng cách sử dụng các yêu cầu-HTML có thể trả về danh sách các URL từ tìm kiếm Google, để bạn có thể phân tích URL trong máy quét web của bạn Dự án hoặc dự án SEO Python.

Nếu bạn chỉ muốn một cách nhanh chóng, miễn phí để loại bỏ kết quả tìm kiếm của Google bằng Python, mà không trả tiền cho dịch vụ API SERP, thì hãy thử gói EcommerCetools của tôi. Nó cho phép bạn xóa kết quả tìm kiếm của Google trong ba dòng mã. Đây là cách mà nó đã thực hiện.

Tải các gói

Đầu tiên, hãy mở một máy tính xách tay Jupyter và nhập các gói dưới đây. Bạn có thể đã có

import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
4,
import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
5 và
import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
6, nhưng bạn có thể cài đặt
import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
7 bằng cách nhập
import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
8, nếu bạn không có nó.

import requests
import urllib
import pandas as pd
from requests_html import HTML
from requests_html import HTMLSession

Nhận nguồn trang

Tiếp theo, chúng tôi sẽ viết một chức năng nhỏ để chuyển URL của chúng tôi cho các yêu cầu-HTML và trả về mã nguồn của trang. Điều này đầu tiên tạo ra một phiên, sau đó lấy phản hồi hoặc ném một ngoại lệ nếu có sự cố. Chúng tôi sẽ cạo các bit thú vị trong bước tiếp theo.

def get_source(url):
    """Return the source code for the provided URL. 

    Args: 
        url (string): URL of the page to scrape.

    Returns:
        response (object): HTTP response object from requests_html. 
    """

    try:
        session = HTMLSession()
        response = session.get(url)
        return response

    except requests.exceptions.RequestException as e:
        print(e)

Scrape kết quả

Đây là một chút mà mọi thứ trở nên thú vị, và hơi hack. Tôi nghi ngờ Google không thích mọi người loại bỏ kết quả tìm kiếm của họ, vì vậy bạn sẽ thấy rằng không có tên lớp CSS thuận tiện mà chúng tôi có thể khai thác. Những người có mặt, dường như thay đổi, khiến những người phế liệu bị phá vỡ. Để làm việc xung quanh điều này, tôi đã sử dụng một cách tiếp cận khác, điều này mạnh mẽ hơn, nhưng có một giới hạn.

Đầu tiên, chúng tôi sử dụng

import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
9 để URL mã hóa truy vấn tìm kiếm của chúng tôi. Điều này sẽ thêm + các ký tự nơi không gian ngồi và đảm bảo rằng thuật ngữ tìm kiếm được sử dụng không phá vỡ URL khi chúng ta nối nó. Sau đó, chúng tôi sẽ kết hợp nó với URL tìm kiếm Google và lấy lại nguồn trang bằng
from bs4 import BeautifulSoup

# The code to get the html contents here.

soup = BeautifulSoup(html, 'html.parser')

# Find all the search result divs
divs = soup.select("#search div.g")
for div in divs:
    # Search for a h3 tag
    results = div.select("h3")

    # Check if we have found a result
    if (len(results) >= 1):

        # Print the title
        h3 = results[0]
        print(h3.get_text())
0.

Thay vì sử dụng lớp CSS hiện tại hoặc XPath để trích xuất các liên kết, tôi đã xuất tất cả các URL tuyệt đối từ trang bằng cách sử dụng

from bs4 import BeautifulSoup

# The code to get the html contents here.

soup = BeautifulSoup(html, 'html.parser')

# Find all the search result divs
divs = soup.select("#search div.g")
for div in divs:
    # Search for a h3 tag
    results = div.select("h3")

    # Check if we have found a result
    if (len(results) >= 1):

        # Print the title
        h3 = results[0]
        print(h3.get_text())
1. Điều này có khả năng chống lại những thay đổi trong mã nguồn Google, nhưng điều đó có nghĩa là sẽ có URL Google cũng có mặt.

Vì nó chỉ có nội dung không phải là google mà tôi quan tâm, nên tôi đã xóa bất kỳ URL nào bằng tiền tố URL liên quan đến Google. Nhược điểm là nó sẽ loại bỏ các URL Google hợp pháp trong SERPS.

def scrape_google(query):

    query = urllib.parse.quote_plus(query)
    response = get_source("https://www.google.co.uk/search?q=" + query)

    links = list(response.html.absolute_links)
    google_domains = ('https://www.google.', 
                      'https://google.', 
                      'https://webcache.googleusercontent.', 
                      'http://webcache.googleusercontent.', 
                      'https://policies.google.',
                      'https://support.google.',
                      'https://maps.google.')

    for url in links[:]:
        if url.startswith(google_domains):
            links.remove(url)

    return links

Chạy chức năng cung cấp cho chúng tôi một danh sách các URL được tìm thấy trên kết quả tìm kiếm của Google cho thuật ngữ đã chọn của chúng tôi, với bất kỳ URL liên quan đến Google nào bị xóa. Đây rõ ràng là một kết quả hoàn hảo cho các kết quả thực tế, tuy nhiên, nó sẽ trả về các miền không phải là Google mà tôi quan tâm.

scrape_google("data science blogs")

['https://medium.com/@exastax/top-20-data-science-blogs-and-websites-for-data-scientists-d88b7d99740',
 'https://data-science-blog.com/',
 'https://blog.feedspot.com/data_science_blogs/',
 'https://github.com/rushter/data-science-blogs',
 'https://365datascience.com/51-data-science-blogs/',
 'https://towardsdatascience.com/best-data-science-blogs-to-follow-in-2020-d03044169eb4',
 'https://www.dataquest.io/blog/',
 'https://www.tableau.com/learn/articles/data-science-blogs',
 'https://www.kdnuggets.com/websites/blogs.html',
 'https://www.thinkful.com/blog/data-science-blogs/']

Bạn có thể điều chỉnh mã phù hợp để chỉ trích xuất các liên kết từ một số phần của SERP, nhưng bạn sẽ thấy rằng bạn sẽ cần cập nhật mã thường xuyên vì mã nguồn được thay đổi thường xuyên. Đối với những gì tôi cần, điều này đã làm tốt công việc.

Muốn văn bản thay thế?

Nếu bạn là người theo tiêu đề, đoạn trích và URL cho mỗi kết quả của công cụ tìm kiếm, hãy thử phương pháp này thay thế. Đầu tiên, tạo một hàm để định dạng và URL mã hóa truy vấn, gửi nó đến Google và hiển thị đầu ra.

def get_results(query):
    
    query = urllib.parse.quote_plus(query)
    response = get_source("https://www.google.co.uk/search?q=" + query)
    
    return response

Tiếp theo, chúng tôi sẽ phân tích cú pháp

from bs4 import BeautifulSoup

# The code to get the html contents here.

soup = BeautifulSoup(html, 'html.parser')

# Find all the search result divs
divs = soup.select("#search div.g")
for div in divs:
    # Search for a h3 tag
    results = div.select("h3")

    # Check if we have found a result
    if (len(results) >= 1):

        # Print the title
        h3 = results[0]
        print(h3.get_text())
2 HTML. Tôi đã tìm kiếm HTML bị che giấu và trích xuất các giá trị CSS hiện tại giữ các giá trị cho kết quả, tiêu đề, liên kết và văn bản đoạn trích. Những thay đổi này thường xuyên, vì vậy điều này có thể không hoạt động trong tương lai mà không điều chỉnh các giá trị này.

def parse_results(response):
    
    css_identifier_result = ".tF2Cxc"
    css_identifier_title = "h3"
    css_identifier_link = ".yuRUbf a"
    css_identifier_text = ".VwiC3b"
    
    results = response.html.find(css_identifier_result)

    output = []
    
    for result in results:

        item = {
            'title': result.find(css_identifier_title, first=True).text,
            'link': result.find(css_identifier_link, first=True).attrs['href'],
            'text': result.find(css_identifier_text, first=True).text
        }
        
        output.append(item)
        
    return output

Cuối cùng, chúng tôi sẽ kết thúc các chức năng trong hàm

from bs4 import BeautifulSoup

# The code to get the html contents here.

soup = BeautifulSoup(html, 'html.parser')

# Find all the search result divs
divs = soup.select("#search div.g")
for div in divs:
    # Search for a h3 tag
    results = div.select("h3")

    # Check if we have found a result
    if (len(results) >= 1):

        # Print the title
        h3 = results[0]
        print(h3.get_text())
3, sẽ đặt mọi thứ ở trên lại với nhau và trả lại một danh sách các từ điển có chứa kết quả.

import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
0

import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
1

import urllib.request

url = 'https://google.com/search?q=Where+can+I+get+the+best+coffee'

# Perform the request
request = urllib.request.Request(url)

# Set a normal User Agent header, otherwise Google will block the request.
request.add_header('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36')
raw_response = urllib.request.urlopen(request).read()

# Read the repsonse as a utf-8 string
html = raw_response.decode("utf-8")
2

Nếu bạn muốn nhanh chóng xóa một số trang kết quả tìm kiếm của Google, thay vì chỉ là trang đầu tiên của kết quả, thay vào đó hãy xem EcommerCetools hoặc điều chỉnh mã ở trên để hỗ trợ phân trang.

Mã không hoạt động?

Mã này đang hoạt động ngày hôm nay, nhưng nó sẽ bị hỏng bất cứ khi nào Google thay đổi các lớp CSS được sử dụng trên các trang kết quả của công cụ tìm kiếm. Nếu nó ngừng hoạt động, bạn sẽ cần xem nguồn của trang, kiểm tra phần tử mà bạn đang cố gắng phân tích và cập nhật định danh CSS cho phù hợp.

Matt Clarke, Thứ Bảy, ngày 13 tháng 3 năm 2021

Làm cách nào để loại bỏ kết quả tìm kiếm trên google trong Python?

Cách cạo kết quả tìm kiếm của Google bằng Python..
Nhập yêu cầu nhập urllib nhập gấu trúc dưới dạng pd từ yêu cầu_html nhập HTML từ yêu cầu_html nhập HTMLSession ..
def get_source (url): "" "Trả lại mã nguồn cho url được cung cấp. ....
def get_results (truy vấn): truy vấn = urllib ..

Làm cách nào để xóa dữ liệu từ kết quả tìm kiếm của Google?

Bạn có thể cạo Google SERP bằng cách sử dụng công cụ tìm kiếm tìm kiếm của Google ...
Đăng nhập vào nền tảng Outcraper và điều hướng đến Google Search Scraper ..
Nhập các truy vấn tìm kiếm mà bạn muốn cạo ..
Chọn Vị trí, Ngôn ngữ và các tham số khác ..
Nhấp vào dữ liệu Scrape Scrape ..

Có hợp pháp để loại bỏ kết quả tìm kiếm của Google không?

Nội dung bị loại bỏ, ngay cả từ các nguồn chất lượng cao, không có các dịch vụ hoặc nội dung hữu ích bổ sung được cung cấp bởi trang web của bạn có thể không cung cấp giá trị gia tăng cho người dùng.Nó cũng có thể cấu thành vi phạm bản quyền.Một trang web cũng có thể bị hạ cấp nếu một số lượng đáng kể các yêu cầu loại bỏ hợp pháp đã được nhận.. It may also constitute copyright infringement. A site may also be demoted if a significant number of valid legal removal requests have been received.

Làm cách nào để có được kết quả tìm kiếm trong Python?

Chúng ta có thể nhận được liên kết đến kết quả tìm kiếm đầu tiên ...
Cài đặt.Gói Google có một phụ thuộc vào BeautifulSoup cần được cài đặt trước ..
Mã Python về cách thực hiện tìm kiếm google bằng tập lệnh Python ..
Ví dụ1: google_search.py ..
Ví dụ 2: Google_search.py ..
Tham khảo: Gói Google Python ..