Hướng dẫn python get url from google search - python lấy url từ tìm kiếm của google

Tôi muốn tạo một tập lệnh trả về tất cả các URL được tìm thấy trong một trang A Google chẳng hạn, vì vậy tôi tạo tập lệnh này: (sử dụng BeautifulSoup)

import urllib2
from BeautifulSoup import BeautifulSoup
page = urllib2.urlopen("https://www.google.dz/search?q=see")
soup = BeautifulSoup(page.read())
links = soup.findAll("a")
for link in links:
    print link["href"]

Và nó trả về kết quả cấm 403 này:

Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden

Bất kỳ ý tưởng để tránh lỗi này hoặc một methode khác để có được các URL từ kết quả tìm kiếm?

Về cơ bản tôi cần 2 điều:

  1. Nhận URL của kết quả tìm kiếm Google đầu tiên

  2. Phân tích bản xem trước nội dung và nhận văn bản sau một số từ cụ thể. Ví dụ: tôi tìm kiếm iPhone iphone11-specs-sumpage, mã của tôi chuyển đến kết quả tìm kiếm đầu tiên và ngay trong chuỗi kết quả tìm kiếm, nó tìm kiếm từ độ dài: và sao chép chuỗi ngay sau khi nó Chỉ vì lợi ích của ví dụ). Làm thế nào để làm điều đó? Tôi thề rằng tôi đã googled rất nhiều, nhưng tôi đã bị mắc kẹt với tất cả các loại vấn đề không liên quan. Ví dụ, tôi đã có thể nhập vào tìm kiếm trên mạng từ Google Googlesearch, một trong những điều tôi không biết gì để sửa nó.

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ó

Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
2,
Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
3 và
Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
4, nhưng bạn có thể cài đặt
Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
5 bằng cách nhập
Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
6, 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

Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
7 để 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
Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
8.

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

Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
9. Đ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

import requests
import urllib
import pandas as pd
from requests_html import HTML
from requests_html import HTMLSession
0 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

import requests
import urllib
import pandas as pd
from requests_html import HTML
from requests_html import HTMLSession
1, 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ả.

def google_search(query):
    response = get_results(query)
    return parse_results(response)

Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
0

Traceback (most recent call last):
  File "C:\Python27\sql\sql.py", line 3, in <module>
    page = urllib2.urlopen("https://www.google.dz/search?q=see")
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 400, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 513, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 438, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 372, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 521, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: Forbidden
1

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 để tìm URL của kết quả tìm kiếm?

Nhận URL trang kết quả tìm kiếm..
Trên máy tính của bạn, truy cập google.com ..
Tìm kiếm trang ..
Ở đầu trình duyệt của bạn, nhấp vào thanh địa chỉ để chọn toàn bộ URL ..
Nhấp chuột phải vào URL đã chọn.Sao chép ..

Làm cách nào để nhận kết quả tìm kiếm của 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 ..

URL chính xác cho Google là gì?

Một số URL của Google bao gồm www.google.com, adwords.googleblog.com và http://www.google.com/intl/en/privacy.Giống như các tòa nhà và nhà ở có một địa chỉ đường phố, các trang web cũng có địa chỉ duy nhất để giúp mọi người định vị chúng.Trên Internet, các địa chỉ này được gọi là URL (trình định vị tài nguyên thống nhất).www.google.com, adwords.googleblog.com, and http://www.google.com/intl/en/privacy. Just as buildings and houses have a street address, webpages also have unique addresses to help people locate them. On the Internet, these addresses are called URLs (Uniform Resource Locators).