如何用 Python 快速抓取 Google 搜索?

如何用 Python 快速抓取 Google 搜索?


如何用 Python 快速抓取 Google 搜索?

如何用 Python 快速抓取 Google 搜索?


文章發佈於公號【數智物語】 (ID:decision_engine),關注公號不錯過每一篇乾貨。


來源 | CSDN(ID:CSDNnews)

作者 | linksc


本文是通過 requests 和 Beautiful Soup 抓取 Google 搜索的快速指南。


如何用 Python 快速抓取 Google 搜索?


自從2011年 Google Web Search API 被棄用以來,我一直在尋找其他的方法來抓取Google。我需要一種方法,讓我的 Python 腳本從 Google 搜索中獲取鏈接。於是,我自己想出了一種方法,而本文正是通過 requests 和 Beautiful Soup 抓取 Google 搜索的快速指南。


首先,讓我們來安裝一些依賴項。請將以下內容保存成文本文件 requirements.txt:


<code>requests
bs4
/<code>


接下來,運行 pip install -r requirements.txt 命令來安裝依賴項。然後將其導入到你的腳本中。


<code>importurllib
importrequests
frombs4importBeautifulSoup
/<code>


為了執行搜索,你需要在URL中為 Google 提供查詢參數。此外,所有空格都必須用+代替。為了構建URL,我們需要設置正確的查詢格式,並其放入q參數中。


<code>query="hackernoonHowToScrapeGoogleWithPython"
query=query.replace('','+')
URL=f"https://google.com/search?q={query}"
/<code>


Google 會針對移動設備和臺式機返回不同的搜索結果。因此,我們需要指定適當的用戶代理。


<code>#desktopuser-agent
USER_AGENT="Mozilla/5.0(Macintosh;IntelMacOSX10.14;rv:65.0)Gecko/20100101Firefox/65.0"
#mobileuser-agent
MOBILE_USER_AGENT="Mozilla/5.0(Linux;Android7.0;SM-G930VBuild/NRD90M)AppleWebKit/537.36(KHTML,likeGecko)Chrome/59.0.3071.125MobileSafari/537.36"
/<code>


發送請求很簡單。但是,requests需要將 user-agent 放在請求的頭部。為了設置正確的頭部,我們必須傳給headers一個字典。


<code>headers={"user-agent":MOBILE_USER_AGENT}
resp=requests.get(URL,headers=headers)
/<code>


接下來,我們需要檢查請求是否成功。最簡單的方法是檢查狀態碼。如果返回200,則表示成功。然後,我們需要將其放入 Beautiful Soup 中以解析內容。


<code>ifresp.status_code==200:
soup=BeautifulSoup(resp.content,"html.parser")
/<code>


接下來是解析數據,並從頁面提取所有的鏈接。我們可以利用 Beautiful Soup 簡單地完成這項工作。在便利每個鏈接時,我們需要將結果存儲到一個列表中。


<code>results=[]
forginsoup.find_all('div',class_='r'):
anchors=g.find_all('a')
ifanchors:
link=anchors[0]['href']
title=g.find('h3').text
item={
"title":title,
"link":link
}
results.append(item)
print(results)
/<code>

這樣就可以了。這個腳本非常簡單,而且容易出錯。但至少它能帶你入門,從此你就可以編寫自己的 Google 爬蟲了。你可以從 GitHub上下載整個腳本,地址是:https://github.com/getlinksc/scrape_google。


原文:https://hackernoon.com/how-to-scrape-google-with-python-bo7d2tal


本文為 CSDN 翻譯,轉載請註明來源出處。


如何用 Python 快速抓取 Google 搜索?


如何用 Python 快速抓取 Google 搜索?

風鳥企業負面信息免費查詢平臺:http://www.yansu.net.cn/


如何用 Python 快速抓取 Google 搜索?


星標我,每天多一點智慧

如何用 Python 快速抓取 Google 搜索?



分享到:


相關文章: