+-
使用Python中的BeautifulSoup从脚本标记中提取文本
你能帮我解决这个问题吗?我希望使用Beautiful soup( Python)从SCRIPT标签(不是Body)中的以下代码中提取电子邮件,电话和名称值.我是Python新手,博客建议使用美丽的汤来提取.

我尝试使用以下代码获取页面 –

fileDetails = BeautifulSoup(urllib2.urlopen('http://www.example.com').read())
results = fileDetails.find(email:")

此Ajax请求代码不再在页面中重复.我们还可以编写try和catch,这样如果它没有在页面中找到它,它就不会抛出任何错误.

<script type="text/javascript" language='javascript'> 
$(document).ready( function (){

   $('#message').click(function(){
       alert();
   });

    $('#addmessage').click(function(){
        $.ajax({ 
            type: "POST",
            url: 'http://www.example.com',
            data: { 
                email: '[email protected]', 
                phone: '9999999999', 
                name: 'XYZ'
            }
        });
    });
});

一旦我得到这个,我也想存储在一个excel文件中.

谢谢你的期待.

最佳答案
作为基于正则表达式的方法的替代,您可以使用 slimit模块解析javascript代码,该模块构建抽象语法树并为您提供获取所有分配并将其放入字典的方法:

from bs4 import BeautifulSoup
from slimit import ast
from slimit.parser import Parser
from slimit.visitors import nodevisitor


data = """
<html>
    <head>
        <title>My Sample Page</title>
        <script>
        $.ajax({
            type: "POST",
            url: 'http://www.example.com',
            data: {
                email: '[email protected]',
                phone: '9999999999',
                name: 'XYZ'
            }
        });
        </script>
    </head>
    <body>
        <h1>What a wonderful world</h1>
    </body>
</html>
"""

# get the script tag contents from the html
soup = BeautifulSoup(data)
script = soup.find('script')

# parse js
parser = Parser()
tree = parser.parse(script.text)
fields = {getattr(node.left, 'value', ''): getattr(node.right, 'value', '')
          for node in nodevisitor.visit(tree)
          if isinstance(node, ast.Assign)}

print fields

打印:

{u'name': u"'XYZ'", u'url': u"'http://www.example.com'", u'type': u'"POST"', u'phone': u"'9999999999'", u'data': '', u'email': u"'[email protected]'"}

在其他领域,有您感兴趣的电子邮件,姓名和电话.

希望有所帮助.

点击查看更多相关文章

转载注明原文:使用Python中的BeautifulSoup从脚本标记中提取文本 - 乐贴网