大家好!今天給你們帶來了使用requests爬取百度和bing搜尋引擎提示詞的簡單例項。
安裝requests:
pip install requests
百度:
import requests
import re
url = 'http://www.baidu.com/su'
params = {
'wd': "python"
}
response = requests.get(url, params=params)
if response.status_code == 200:
#使用正規表式提取搜尋建議
match = re.search(r's:\[(.*?)\]', response.text)
if match:
suggestions_str = match.group(1)
#利用正規表式提取每個建議,並以換行分隔打印
suggestions_list = re.findall(r'"([^"]*)"', suggestions_str)
print('\n'.join(suggestions_list))
輸出:
python
python入門教程(非常詳細)
python下載
python編程
python程式碼大全
python什麽東西
python學了能幹嘛
python怎麽讀
python中的%用法
python能做什麽
bing:
import requests
url = 'https://api.bing.com/osjson.aspx'
params = {
'query': "python"
}
response = requests.get(url, params=params)
if response.status_code == 200:
suggestions = response.json()[1]
print('\n'.join(suggestions))
輸出:
python
python下載
python123
python安裝
python官網
python教程
python.org
pythonfor迴圈
python爬蟲
python3
python字典
pythonlist
requests參數簡要:
params:用於向 URL 查詢中傳遞參數。
data:用於向伺服器送出表單數據或者 JSON 數據。
json:用於向伺服器送出 JSON 數據。
headers:用於設定 HTTP 請求頭部。
cookies:用於發送 Cookie。
auth:用於 HTTP 認證相關設定。
files:用於上傳檔。
timeout:用於設定請求超時時間。
allow_redirects:用於設定重新導向。
proxies:用於設定代理。
verify:用於設定是否驗證 SSL 證書。
stream:用於處理響應的數據流。
cert:用於客戶端證書認證。