【问题标题】:Parsing URL through Python通过 Python 解析 URL
【发布时间】:2015-06-09 20:55:22
【问题描述】:

我需要解析

http://www.webpagetest.org/breakdown.php?test=150325_34_0f581da87c16d5aac4ecb7cd07cda921&run=2&cached=0

如果您查看上述网址的来源,您会发现

预期输出

fvRequests= css
fvRequests=7

【问题讨论】:

  • fvRequests.setValue(0, 0, 'css') fvRequests.setValue(0, 1, 7) fvBytes.setValue(0, 0, 'css') fvBytes.setValue(0, 1, 110557)

标签: python python-2.7 parsing web-scraping url-parsing


【解决方案1】:
import re
import urllib2



if __name__ == "__main__":
    url = 'http://www.webpagetest.org/breakdown.php?test=150325_34_0f581da87c16d5aac4ecb7cd07cda921&run=2&cached=0'

    # http request
    response = urllib2.urlopen(url)
    html = response.read()
    response.close()

    # finding values in html
    results = re.findall(r'fvRequests\.setValue\(\d+, \d+, \'?(.*?)\'?\);', html)
    keys = results[::2]
    values = results[1::2]

    # creating a dictionary
    output = dict(zip(keys, values))

    print output

【讨论】:

  • 非常感谢,真的很有帮助
【解决方案2】:

想法是使用BeautifulSoup 定位脚本,并使用正则表达式模式查找fvRequests.setValue() 调用并提取第三个参数的值:

import re

from bs4 import BeautifulSoup
import requests


pattern = re.compile(r"fvRequests\.setValue\(\d+, \d+, '?(\w+)'?\);")

response = requests.get("http://www.webpagetest.org/breakdown.php?test=150325_34_0f581da87c16d5aac4ecb7cd07cda921&run=2&cached=0")
soup = BeautifulSoup(response.content)

script = soup.find("script", text=lambda x: x and "fvRequests.setValue" in x).text
print(re.findall(pattern, script))

打印:

[u'css', u'7', u'flash', u'0', u'font', u'0', u'html', u'14', u'image', u'80', u'js', u'35', u'other', u'14']

你可以更进一步,将列表打包成一个字典(解决方案取自here):

dict(zip(*([iter(data)] * 2)))

会产生:

{
    'image': '80', 
    'flash': '0', 
    'js': '35', 
    'html': '14',  
    'font': '0', 
    'other': '14', 
    'css': '7'
}

【讨论】:

  • 太棒了,非常感谢它真的很有帮助
猜你喜欢
  • 2014-04-03
  • 2021-03-04
  • 2013-02-02
  • 2015-09-24
  • 1970-01-01
  • 2014-05-13
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
相关资源
最近更新 更多