使用 python、beautifulsoup 和机械化选择下拉菜单

Selecting dropdown with python, beautifulsoup and mechanize

我正在尝试从似乎是 ajax 网页的内容中抓取数据。数据每秒自动刷新。

http://daytonama.clubspeedtiming.com/sp_center/livescore.aspx

我似乎无法确定我是否选择了正确的下拉菜单,或者页面是否正在更改为我需要抓取的数据。

谢谢

!/usr/bin/env python
import mechanize
from bs4 import BeautifulSoup
import re
import urllib2
#import html2text
import time

# Set credentials
venue = "sp" # Manchester (ma), Milton Keynes (mk), Sandown Park (sp), Tamworth (ta)
track = "3" # Manchester (3), Milton Keynes (1)

# Open new browser
br = mechanize.Browser()

# Target live timing page
resp = br.open("http://daytona"+ venue +".clubspeedtiming.com/sp_center/livescore.aspx")
html = resp.read()

# Grab live data table
soup = BeautifulSoup(html, "html5lib")

# Select track layout
select_node = soup.findAll('select', attrs={'name': 'ddlTrack'})

if select_node:
    for option in select_node[0].findAll('option'):
        print ''
        #print option.text

br.select_form( name = 'form1' )
br.form['ddlTrack'] = [track]

grid = soup.find("div", { "id" : "grid" })
print ''.join(map(str, grid.contents))

通常ajax调用由目标网页上的JS运行异步请求触发

据我所知mechanize.Browser不是真正的浏览器,它不能执行和理解javascript,它不能发送异步请求。

在我看来,这就是您实际尝试输入 BS4 的页面没有真正加载的原因,这就是为什么您不能 select。

我可以想到两个选项:

  1. 使用 selenium or phantomJS(headless) 作为浏览器。
  2. 分析网络并尝试找出网页正在执行的请求,然后仅模拟 ajax 请求,而不是尝试加载整个页面