2017-04-18 159 views
0

我爲使用Python請求搜索以下網站:https://www.investing.com/的術語「耐用品訂單美國」的Python POST請求

我檢查在檢查面板的「網絡」選項卡,現在看來,這是根本「quotes_search_text」:用以下形式完成的「耐用品訂單美國」

所以,我試圖使用python:

URL = 'https://www.investing.com/' 
data = {'quotes_search_text':'Durable Goods Orders US'} 
resp = requests.post(URL, data=data, headers={ 'User-Agent': 'Mozilla/5.0', 'X-Requested-With': 'XMLHttpRequest'}) 

然而,這並不返回結果,而做手工,我可以看到。 所有搜索結果中應該有「GS-標題」作爲類屬性(按照頁面檢查),但是當我做的:

soup = BeautifulSoup(resp.text, 'html.parser') 
soup.select(".gs-title") 

我看不出有什麼結果...... 有POST請求的某些方面我沒有考慮到? (這裏是一個完整的菜鳥)

+0

我相信你的'find_all'選擇器正在尋找一個類屬性,當它期待一個HTML標記。 –

+0

@double_j不,我正在尋找一個類屬性...在這裏什麼目標元素看起來像:'United States Durable Goods Orders MoM' –

+0

沒關係,但BeautifulSoup永遠不會找到你現在的方式標籤。你應該這樣寫:'soup.find_all('a',{'class':'gs-title'})' –

回答

1

在聊天中詳細地講過這個之後,有很多變化。爲了檢索您要查找的信息,您需要運行正在運行的JS。您可以將query變量更改爲任何您想要的。

import requests 
import json 
from urllib.parse import quote_plus 

URL = 'https://www.googleapis.com/customsearch/v1element' 

query = 'Durable Goods Orders US' 
query_formatted = quote_plus(query) 

data = { 
    'key':'AIzaSyCVAXiUzRYsML1Pv6RwSG1gunmMikTzQqY', 
    'num':10, 
    'hl':'en', 
    'prettyPrint':'true', 
    'source':'gcsc', 
    'gss':'.com', 
    'cx':'015447872197439536574:fy9sb1kxnp8', 
    'q':query_formatted, 
    'googlehost':'www.google.com' 
} 
headers = { 
    'User-Agent':'Mozilla/5.0', 
    'Referer':'https://www.investing.com/search?q=' + query_formatted, 
} 
resp = requests.get(URL, params=data, headers=headers) 

j = json.loads(resp.text) 
# print(resp.text) 
for r in j['results']: 
    print(r['title'], r['url'])