python.js页面解析

2024-06-01 02:05:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个网页http://timetable.ait.ie/js/filter.js,我真的需要分析这个网页。在过去的几天里,我一直在使用BeautifulSoup来解析html页面,我真的明白了我在那里做的事情,但是这个.js文件让我很难受。你知道吗

目前我正在使用以下代码:

import urllib
page = urllib.urlopen("http://timetable.ait.ie/js/filter.js")
pageInfo = page.read()

它返回一个包含18283行代码的整个文件的字符串。在我试图将员工姓名放在最下面的代码中,有一个数组:

staffarray[373][0] = "BRADY, DAMIEN";
staffarray[373][1] = "SCI";
staffarray[373][2] = "BRADY001608";

我需要[0]和[1]中的值,然后用这些值构建一个数据库,以便以后引用。你知道吗

我已经试过regex来寻找staffarray,但是我对得到这个信息感到非常沮丧。有人能帮我吗。你知道吗


Tags: 文件代码http网页htmlpagejs页面
2条回答

您可以编写带有捕获组的regexp模式:

import re
with open('filter.js') as file:
    pattern = r'staffarray\[(?P<first_index>\d+)\]\s*\[(?P<second_index>\d+)\] = "(?P<name>.+)"'
    for line in file:
        match = re.search(pattern, line)
        if match:
            first_index, second_index, name = match.groups()
            # do something with data

如果您对regex有问题,那么使用标准的字符串函数和切片。你知道吗

首先将代码分成行,然后搜索staffarray[[0][1]。最后使用切片。你知道吗

import urllib

req = urllib.urlopen("http://timetable.ait.ie/js/filter.js")
lines = req.read().split('\n')

for x in lines:
    if 'staffarray[' in x:
        if '[0] = ' in x:
            start = x.find('"')+1
            end = -3
            print '0', x[start:end]
        elif '[1] = ' in x:
            start = x.find('"')+1
            end = -3
            print '1', x[start:end]

相关问题 更多 >