如何用 beautifulsoup 抓取隐藏的 table

How to scrape a hidden table with beautifulsoup

这是关于用 beautifulsoup 抓取一个隐藏的 table。

正如您在 this website 中看到的那样,有一个按钮 "choisissez votre séance",当我们单击它时,将显示一个 table。

当我单击检查 table 元素时,我可以看到包含价格等属性的标签。但是,当我查看该网站的源代码时,我找不到这些信息。

table 'display : none' 的代码中有些东西我认为会影响这个,但我找不到解决方案。

页面似乎正在使用 AJAX 并在后台加载定价数据。使用 Chrome 我按 F12 并在网络选项卡下查看。当我点击 "choisissez votre séance" 按钮时,我注意到这个地址有一个 POST:

'https://www.ticketmaster.fr/fr/manifestation/holiday-on-ice-billet/idmanif/446304'

这对您来说是个好消息,因为您不需要抓取 HTML 数据,您只需向 API.[=12= 提供 ID(在页面源中) ]

在下面的代码中我是

  1. 请求初始页面
  2. 正在收集 cookie
  3. 发布 ID(数据)和我们收集的 cookie
  4. 返回您需要进一步处理的 JSON 数据(变量 J)

希望以下内容对您有所帮助!

干杯, 亚当


import requests
from bs4 import BeautifulSoup

h = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}
s = requests.session()

initial_page_request = s.get('https://www.ticketmaster.fr/fr/manifestation/holiday-on-ice-billet/idmanif/446304',headers=h)

soup = BeautifulSoup(initial_page_request.text,'html.parser')
idseanc = soup.find("select",{"id":"sessionsSelect"})("option")[0]['value'].split("_")[1]

cookies = initial_page_request.cookies.get_dict()

headers = {
    'Origin': 'https://www.ticketmaster.fr',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'en-GB,en-US;q=0.9,en;q=0.8',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36',
    'Content-Type': 'application/json; charset=UTF-8',
    'Accept': '*/*',
    'Referer': 'https://www.ticketmaster.fr/fr/manifestation/holiday-on-ice-billet/idmanif/446304',
    'X-Requested-With': 'XMLHttpRequest',
    'Connection': 'keep-alive',
}

data = {'idseanc':str(idseanc)}

response = s.post('https://www.ticketmaster.fr/planPlacement/FindPrices/connected/false/idseance/2870471', headers=headers, cookies=cookies, data=data)

j = response.json()