2017-04-21 80 views
0

我無法從使用BeautifulSoup的網頁中提取特定鏈接時遇到問題。具體的網頁是http://punchdrink.com/recipe-archives/?filter-spirit__term=Gin在Python中找不到使用美麗湯的特定鏈接

當我檢查的源代碼,我看到,我想抓住的鏈接,特別是鏈接到食譜(例如:http://punchdrink.com/recipes/breakfast-martini/),但是當我使用BeautifulSoup,這些鏈接顯示不出來在HTML中。

這裏是我的代碼爲抓住HTML:

def drinkScraper(url, searchTerm): 
    res = requests.get(url) 
    res.raise_for_status() 
    soup = bs4.BeautifulSoup(res.text) 

印刷湯給HTML沒有提到任何鏈接的菜譜在該網頁。

我想抓住這個網站鏈接到他們檔案中的所有食譜,但我似乎無法弄清楚這一點。

感謝您的任何幫助。

+0

因爲它是一個動態的網站,你必須檢查Ajax請求得到的網址。 – amigcamel

+0

@amigcamel謝謝!我最終使用硒來查找鏈接。儘管如此,我會在未來更多地考慮你的建議。 –

回答

0

儘管如上所述您可以使用selenium,但您也可以通過遵循XHR請求並通過requests進行模擬來學習。如果您注意到在打開Firebug或Chrome開發人員工具時搜索某個術語,它會請求一個API(通過XHR)並以json格式返回結果。您可以簡單地請求參數並解析結果。

像這樣:

from bs4 import BeautifulSoup 
import requests 

jsonRequestData = '{"requests":[{"indexName":"wp_posts_recipe","params":"query=&hitsPerPage=1000&maxValuesPerFacet=100&page=0&distinct=false&facetingAfterDistinct=true&filters=record_index%3D0&facets=%5B%22spirit%22%2C%22style%22%2C%22season%22%2C%22flavor_profile%22%2C%22family%22%5D&tagFilters=&facetFilters=%5B%22spirit%3AGin%22%5D"}]}' 
headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'application/json'} 

response = requests.post('http://h0iee3ergc-2.algolianet.com/1/indexes/*/queries?x-algolia-agent=Algolia%20for%20vanilla%20JavaScript%20(lite)%203.21.1%3Binstantsearch.js%201.11.6%3BJS%20Helper%202.19.0&x-algolia-application-id=H0IEE3ERGC&x-algolia-api-key=9a128c4989675ec375c59a2de9ef3fc1', headers=headers, data=jsonRequestData) 

for hit in response.json()["results"][0]["hits"]: 
    print ("%s (%s)" % (hit["post_title"], hit["permalink"])) 

哪裏jsonRequestData是數據form post data,在那裏你可以改變搜索項和headers的是,你要發送的報頭。

它會輸出:

State Street Bloody Mary (http://punchdrink.com/recipes/state-street-bloody-mary/) 
I'm Ya Huckleberry (http://punchdrink.com/recipes/im-ya-huckleberry/) 
Girl From Cadiz (http://punchdrink.com/recipes/girl-from-cadiz/) 
Breakfast Martini (http://punchdrink.com/recipes/breakfast-martini/) 
Juniperotivo (http://punchdrink.com/recipes/juniperotivo/) 
....