python - 美汤刮一 table

标签 python web-scraping beautifulsoup

我正在尝试从该网站抓取价格表(购买是,价格和契约(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')

关于python - 美汤刮一 table ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45178001/

相关文章:

python - 在python beautifulsoup中遍历多个div,输出到df然后csv

python - 使用 BeautifulSoup 查找具有不同 id 值的所有 div 元素

python - 在 Python 上的 Google App Engine 中按实体键名过滤

python - 使用 odeint() 在 Python 中进行摆锤模拟,但不太像摆锤一样工作

python - 在 scrapy 中启用 deltafetch

javascript - 用于弹出窗口内分页和网页抓取的动态 CasperJS 步骤数

python - 为什么我得到 "IndexError: list index out of range",在 for 循环期间,漂亮的汤解析中途?

python - 如何使用 UUID

Python 日志记录适用于 Windows,但不适用于 Mac OS

python - 使用 python selenium/Beautifulsoup 从多个页面提取数据