使用BeautifulSoup获取属性值

10

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

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

<script>some JS</script>

我可以获取第二种情况下的JavaScript代码,也就是当JS代码直接写在<script>标签中时。

但是是否有办法可以获取第一种情况下(即提取<script>标签内所有src标签的值,如http://example.com/something.js)的src值呢?

以下是我的代码:

#!/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


如果您对答案感到满意,请接受您满意的答案。 - Venkateshwaran Selvaraj
3个回答

26

只有当src存在时,它才会获取所有src值。否则,它将跳过该<script>标记。

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

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


5
从脚本节点中获取'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') <==== 

输出结果是'None',源代码是None.. 但是如果我使用n.get('type'),它会显示结果"text/javascript"。 为什么src会有这个问题? - aditya.gupta
嗯...它应该可以工作,我在我的系统中尝试过了。'n'的输出是什么? - rajpy
输出结果为“无”。 - aditya.gupta

1

这应该可以工作,你只需要过滤查找所有的脚本标签,然后确定它们是否有“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

这句话的意思是:“这个的输出结果是”。
http://example.com/something.js
some JS

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接