【问题标题】:How to use Beautiful Soup to extract function string in <script> tag?如何使用 Beautiful Soup 提取 <script> 标签中的函数字符串?
【发布时间】:2016-12-06 20:35:07
【问题描述】:

在给定的 .html 页面中,我有一个这样的脚本标签: 如何使用美汤提取“function getData()”下的“rerun”信息?

<script>
function getData()
{
	return "zip,city,state,MedianIncome,MedianIncomeRank,CostOfLivingIndex,CostOfLivingRank\n10452,Bronx,NY,20606,2,147.7,74";
}

function getResultsCount()
{
	return "1";
}

</script>

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    可以说是最简单的一种方法是使用regular expression 来定位元素并提取所需的字符串:

    import re
    
    from bs4 import BeautifulSoup
    
    data = """
    <script>
    function getData()
    {
        return "zip,city,state,MedianIncome,MedianIncomeRank,CostOfLivingIndex,CostOfLivingRank\n10452,Bronx,NY,20606,2,147.7,74";
    }
    
    function getResultsCount()
    {
        return "1";
    }
    
    </script>
    """
    
    soup = BeautifulSoup(data, "html.parser")
    
    pattern = re.compile(r'return "(.*?)";$', re.MULTILINE | re.DOTALL)
    script = soup.find("script", text=pattern)
    
    print(pattern.search(script.text).group(1))
    

    打印:

    zip,city,state,MedianIncome,MedianIncomeRank,CostOfLivingIndex,CostOfLivingRank
    10452,Bronx,NY,20606,2,147.7,74
    

    或者,您也可以使用 JavaScript 解析器,例如 slimit,例如 here

    【讨论】:

    • 更新如下代码时出现错误(AttributeError: 'NoneType' object has no attribute 'text')。 url = "zipwho.com/?zip=91709&city=&filters=------_--&state=&mode=zip" 数据 = urlopen(url).read() 汤 = BeautifulSoup(data, "html.parser")跨度>
    • @jerry9855 首先,URL不应该是http://zipwho.com/?zip=91709&amp;city=&amp;filters=--_--_--_--&amp;state=&amp;mode=zip吗?此外,您应该从html.parser 切换到html5lib(并安装html5lib 模块)。
    猜你喜欢
    • 2016-11-27
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2020-05-04
    相关资源
    最近更新 更多