python - 如何使用 Python、BeautifulSoup 和 mechanize 从表中提取 Web 数据

标签 python beautifulsoup mechanize

我想从此站点上的表中提取数据:http://www.pgatour.com/r/stats/info/xm.html?101 然后将其另存为 .csv 并将其带入 iWorks Numbers 工作表中。 我一直在尝试使用 Python、BeautifulSoup 和 mechanize。我一直在不知情的情况下通过查看其他示例进行尝试,但没有成功。我已经走到这一步了:

from BeautifulSoup import BeautifulSoup, SoupStrainer
from mechanize import Browser
import re
br = Browser()
response = br.open("http://www.pgatour.com/r/stats/info/xm.html?101").read()

然后我用 firebug 查看代码,我猜我需要解析 <tbody> 之间的数据。和</tbody> 。但我不知道该怎么做。 非常感谢任何帮助。

最佳答案

在主页中,旅游统计信息似乎是由 JavaScript 填充的 <div class="tourViewData"> ... populateDDs(); BS 不解析 Javascript,请参阅许多其他 SO 问题。 (我不知道如何解决该部分。最坏的情况是,选择该 HTML 选择并将其保存为本地 html 文件,作为解决方法。)

首先,将 s 设置为该 URL 的 BeautifulSoup 对象(我使用斜纹布而不是原始 Mechanize ,将您的 Mechanize 等效项放在这里):

from BeautifulSoup import BeautifulSoup, SoupStrainer
#from mechanize import Browser
from twill.commands import *
import re

go("http://www.pgatour.com/r/stats/info/xm.html?101")
s = BeautifulSoup(get_browser().get_html())

无论如何,您要查找的统计数据表就是标有 <tbody><tr class="tourStatTournHead"> 的表。 。 只是为了让事情有点古怪,其行中的标记属性交替定义为 <tr class="tourStatTournCellAlt"<tr class=""... 。 我们应该搜索第一个<tr class="tourStatTournCellAlt" ,然后处理每个 <tr>之后的表中,标题行 ( <tr class="tourStatTournHead"> ) 除外。

迭代行:

tbl = s.find('table', {'class':'tourStatTournTbl'})

def extract_text(ix,tg):
    if ix==2: # player name field, may be hierarchical
        tg = tg.findChildren()[0] if (len(tg.findChildren())>0) else tg
    return tg.text.encode()

for rec in tbl.findAll('tr'): # {'class':'tourStatTournCellAlt'}):
    # Skip header rows
    if (u'tourStatTournHead' in rec.attrs[0]):
        continue        
    # Extract all fields
    (rank_tw,rank_lw,player,rounds,avg,tot_dist,tot_drives) = \
        [extract_text(i,t) for (i,t) in enumerate(rec.findChildren(recursive=False))]
    # ... do stuff

我们为玩家名称添加了一个辅助函数(如果它嵌入了 Titleist Logo ,它可能是分层的,也可能不是分层的。) 可能您希望将大多数字段转换为 int(),除了 player(string) 和 avg(float);如果是这样,请记住从排名字段中删除可选的“T”(表示并列),并从 tot_dist 中删除逗号。

关于python - 如何使用 Python、BeautifulSoup 和 mechanize 从表中提取 Web 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7072139/

相关文章:

python - 如何从网站上的最后一个表中抓取数据

html - 如何使用 BeautifulSoup 识别各种网站的菜单?

python - 在Python中使用BeautifulSoup获取HTML源中的JS var值

python - 使用 beautifulsoup 抓取 <h2> 标签

Ruby mechanize - 区分两种形式的内容

python - 环境变量

python - libgmail login() 运行时出错

python - Beautifulsoup 在抓取 YouTube channel 时返回空列表

python - 具有两个预训练 ResNet 50 的连体神经网络 - 测试模型时出现奇怪的行为

python - 线程顺序循环还是并发循环?