尽管如上所述您可以使用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/)
....
因为它是一个动态的网站,你必须检查Ajax请求得到的网址。 – amigcamel
@amigcamel谢谢!我最终使用硒来查找链接。尽管如此,我会在未来更多地考虑你的建议。 –