【问题标题】:Getting attribute's value using BeautifulSoup使用 BeautifulSoup 获取属性值
【发布时间】:2013-09-14 23:53:45
【问题描述】:

我正在编写一个 python 脚本,它将在从网页解析后提取脚本位置。 假设有两种情况:

<script type="text/javascript" src="http://example.com/something.js"></script>

<script>some JS</script>

我能够从第二种情况中获取 JS,即 JS 写入标签中。

但是有什么办法,我可以从第一个场景中获取 src 的值(即提取脚本中 src 标记的所有值,例如http://example.com/something.js

这是我的代码

#!/usr/bin/python

import requests 
from bs4 import BeautifulSoup

r  = requests.get("http://rediff.com/")
data = r.text
soup = BeautifulSoup(data)
for n in soup.find_all('script'):
    print n 

输出:一些 JS

需要输出http://example.com/something.js

【问题讨论】:

  • 如果您对答案感到满意,请接受您满意的答案。

标签: python python-2.7 beautifulsoup


【解决方案1】:

只有当它们存在时,它才会获取所有src 值。否则它会跳过 &lt;script&gt; 标签

from bs4 import BeautifulSoup
import urllib2
url="http://rediff.com/"
page=urllib2.urlopen(url)
soup = BeautifulSoup(page.read())
sources=soup.findAll('script',{"src":True})
for source in sources:
 print source['src']

我得到以下两个 src 值作为结果

http://imworld.rediff.com/worldrediff/js_2_5/ws-global_hm_1.js
http://im.rediff.com/uim/common/realmedia_banner_1_5.js

我想这就是你想要的。希望这有用。

【讨论】:

    【解决方案2】:

    这应该可行,您只需过滤以查找所有脚本标签,然后确定它们是否具有“src”属性。如果他们这样做,那么 javascript 的 URL 包含在 src 属性中,否则我们假设 javascript 在标记中

    #!/usr/bin/python
    
    import requests 
    from bs4 import BeautifulSoup
    
    # Test HTML which has both cases
    html = '<script type="text/javascript" src="http://example.com/something.js">'
    html += '</script>  <script>some JS</script>'
    
    soup = BeautifulSoup(html)
    
    # Find all script tags 
    for n in soup.find_all('script'):
    
        # Check if the src attribute exists, and if it does grab the source URL
        if 'src' in n.attrs:
            javascript = n['src']
    
        # Otherwise assume that the javascript is contained within the tags
        else:
            javascript = n.text
    
        print javascript
    

    this的输出是

    http://example.com/something.js
    some JS
    

    【讨论】:

      【解决方案3】:

      从脚本节点获取'src'。

      import requests 
      from bs4 import BeautifulSoup
      
      r  = requests.get("http://rediff.com/")
      data = r.text
      soup = BeautifulSoup(data)
      for n in soup.find_all('script'):
          print "src:", n.get('src') <==== 
      

      【讨论】:

      • 得到输出“无”。 src: None src: None .. 但是如果我执行 n.get('type') 它会显示结果“text/javascript” 为什么 src 有这个问题?
      • 嗯..它应该可以工作,我在我的系统中尝试过。 'n' 的输出是什么?
      • 输出为“无”。
      猜你喜欢
      • 2016-09-19
      • 2018-11-05
      • 2021-05-21
      • 2015-08-28
      • 2017-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-06
      相关资源
      最近更新 更多