gpt4 book ai didi

python - 使用 BeautifulSoup 获取属性值

转载 作者:太空狗 更新时间:2023-10-29 20:33:46 26 4
gpt4 key购买 nike

我正在编写一个 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

最佳答案

它将获得所有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

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

关于python - 使用 BeautifulSoup 获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18733023/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com