繁体   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