簡體   English   中英

在Python中使用Beautiful Soup無法找到特定鏈接

[英]Can't find a specific link using Beautiful Soup in Python

我無法使用BeautifulSoup從網頁中提取特定鏈接。 具體的網頁是http://punchdrink.com/recipe-archives/?filter-spirit__term=Gin

當我檢查源代碼時,會看到我要抓取的鏈接,特別是指向食譜的鏈接(例如: 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沒有引用該頁面上任何食譜的鏈接。

我正在嘗試從該網站抓取其檔案庫中所有食譜的鏈接,但我似乎無法弄清楚。

謝謝你的幫助。

盡管selenium ,您可以使用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/)
....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM