[英]Using BeautifulSoup to scrape Google top feedback results for phone number
您使用的find
方法錯誤。 您需要提供標簽的名稱,然后提供可用於唯一標識特定標簽的任何屬性。 您可以使用檢查工具找到電話號碼所在的標簽。
另外,您可能需要找到您的user-agent
並將其作為標題傳遞,以請求從Google獲得完全相同的響應。 只需在Google中搜索“我的用戶代理是什么”即可找到您的用戶代理。
from bs4 import BeautifulSoup
import requests
headers={
'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36'
}
r=requests.get('https://www.google.com/search?q=university+of+alabama+phone',headers=headers)
soup=BeautifulSoup(r.text,'html.parser')
ph_no=soup.find('div',class_='Z0LcW').text
print(ph_no)
產量
+1 205-348-6010
文檔
不能保證這適用於所有對象,但是您可以使用CSS類選擇器通過select_one檢索第一個結果,並包裝在try中,
import requests
from bs4 import BeautifulSoup
query = input("What would you like to search: ")
query = query.replace(" ","+")
query = "https://www.google.com/search?q=" + query + "phone"
r = requests.get(query)
html_doc = r.text
soup = BeautifulSoup(html_doc, 'lxml')
try:
s = soup.select_one(".mrH1y").text
except:
s = "not found"
print(s)
QHarr和Bitto Bennichan 的答案中提供的CSS
選擇器在 HTML 布局中的當前 Google Organic 結果中不存在,並且會引發錯誤(如果不使用try/except
塊)。
目前,是這樣的:
>>> phone = soup.select_one('.mw31Ze').text
"+1 205-348-6010"
此外,它向您返回None
,因為沒有指定user-agent
因此 Google 阻止了您的請求,並且您收到了帶有某種錯誤的不同 HTML。
因為默認requests
user-agent
是python-requests 。 谷歌理解它並阻止請求,因為它不是“真正的”用戶訪問。檢查您的user-agent
是什么。
傳遞user-agent
介紹請求標頭:
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
requests.get("YOUR_URL", headers=headers)
代碼:
import requests, lxml
from bs4 import BeautifulSoup
headers = {
"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
}
params = {
"hl": "en",
"gl": "uk" # contry to search from. uk = United Kingdom. us = United States
}
query = input("What would you like to search: ")
query = f"https://www.google.com/search?q={query} phone"
response = requests.get(query, headers=headers, params=params)
soup = BeautifulSoup(response.text, 'lxml')
try:
phone = soup.select_one(".X0KC1c").text
except: phone = "not found"
print(phone)
'''
What would you like to search: university of alabama
+1 205-348-6010
'''
或者,您可以使用來自 SerpApi 的Google Knowledge Graph API來實現相同的目的。 這是一個帶有免費計划的付費 API。
您的情況的不同之處在於您只需要遍歷結構化 JSON 並獲取您想要的數據,而不是弄清楚為什么某些事情會中斷並且無法正常工作,並且您不必隨着時間的推移維護解析器如果某些選擇器將被更改並導致解析器制動。
集成代碼:
from serpapi import GoogleSearch
params = {
"api_key": "YOUR_API_KEY",
"engine": "google",
"q": "university of alabama phone",
"gl": "uk",
"hl": "en"
}
search = GoogleSearch(params)
results = search.get_dict()
phone = results['knowledge_graph']['phone']
print(phone)
# +1 205-348-6010
免責聲明,我為 SerpApi 工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.