Очистка поиска Google с помощью BeautifulSoup - PullRequest
0 голосов
/ 15 ноября 2018

Я хотел очистить несколько страниц поиска Google. До сих пор мне удавалось скрести только первую страницу, но как я мог сделать это для нескольких страниц.

from bs4 import BeautifulSoup
import requests
import urllib.request
import re
from collections import Counter

def search(query):
    url = "http://www.google.com/search?q="+query

    text = []
    final_text = []

    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text,"html.parser")

    for desc in soup.find_all("span",{"class":"st"}):
        text.append(desc.text)

    for title in soup.find_all("h3",attrs={"class":"r"}):
        text.append(title.text)

    for string in text:
        string  = re.sub("[^A-Za-z ]","",string)
        final_text.append(string)

    count_text = ' '.join(final_text)
    res = Counter(count_text.split())

    keyword_Count = dict(sorted(res.items(), key=lambda x: (-x[1], x[0])))

    for x,y in keyword_Count.items():
        print(x ," : ",y)


search("girl")

Ответы [ 2 ]

0 голосов
/ 16 ноября 2018
url = "http://www.google.com/search?q=" + query + "&start=" + str((page - 1) * 10)
0 голосов
/ 16 ноября 2018

как комментарий выше, вам нужен URL следующей страницы и поместите код в цикл

def search(query):
    url = "https://www.google.com/search?hl=en&q=" + query
    while url:
        text = []
        ....
        ....
        for x,y in keyword_Count.items():
            print(x ," : ",y)

        # get next page url
        url = soup.find('a', id='pnnext')
        if url:
            url = 'https://www.google.com/' + url['href']
        else:
            print('no next page, loop ended')
            break

Чтобы заставить soup.find('a', id='pnnext') работать, вам может потребоваться установить user-agent для запросов

...