Skip to main content
 首页 » 编程设计

python之美汤刮一 table

2025年02月15日7zhujiabin

我正在尝试从该网站抓取价格表(购买是,价格和契约(Contract)可用):https://www.predictit.org/Contract/7069/Will-the-Senate-pass-the-Better-Care-Reconciliation-Act-by-July-31#prices .

这是我的(显然是非常初步的)代码,现在结构化只是为了找到表格:

from bs4 import BeautifulSoup 
import requests 
from lxml import html 
import json, re 
 
url = "https://www.predictit.org/Contract/7069/Will-the-Senate-pass-the-Better-Care-Reconciliation-Act-by-July-31#prices" 
 
ret = requests.get(url).text 
 
soup = BeautifulSoup(ret, "lxml") 
 
try: 
    table = soup.find('table') 
    print table 
except AttributeError as e: 
    print 'No tables found, exiting' 

代码查找并解析一个表;然而,它是错误的(不同选项卡上的数据表 https://www.predictit.org/Contract/7069/Will-the-Senate-pass-the-Better-Care-Reconciliation-Act-by-July-31#data )。

如何解决此错误以确保代码识别正确的表?

请您参考如下方法:

正如@downshift 在评论中提到的,该表是使用 xhr 请求生成的 js。
因此,您可以使用 Selenium 或直接请求网站的 api。

使用第二个选项:

url = "https://www.predictit.org/PrivateData/GetPriceListAjax?contractId=7069" 
ret = requests.get(url).text 
soup = BeautifulSoup(ret, "lxml") 
table = soup.find('table')