2017-02-10 96 views
0

我是Beautifulsoup的新手,似乎遇到了问题。我写的代码对我而言是正确的,但输出是空的。它没有显示任何价值。BeautifulSoup不返回任何值

import requests 
from bs4 import BeautifulSoup 

url = requests.get("https://www.nseindia.com/") 

soup = BeautifulSoup(url.content, "html.parser") 

nifty = soup.find_all("span", {"id": "lastPriceNIFTY"}) 

for x in nifty: 
    print x.text 

回答

1

该网页似乎是通过javascript呈现的。 requests将无法​​获取JavaScript加载的内容,它将在JavaScript呈现之前获取部分页面。您可以使用dryscrape库这个像这样:

import dryscrape 
from bs4 import BeautifulSoup 

sess = dryscrape.Session() 
sess.visit("https://www.nseindia.com/") 
soup = BeautifulSoup(sess.body(), "lxml") 
nifty = soup.select("span[id^=lastPriceNIFTY]") 
print nifty[0:2] #printing sample i.e first two entries. 

输出:

[<span class="number" id="lastPriceNIFTY 50"><span class="change green">8,792.80 </span></span>, <span class="value" id="lastPriceNIFTY 50 Pre Open" style="color:#000000"><span class="change green">8,812.35 </span></span>] 
+0

我不能安装dryscrape。每当我尝试通过点对点安装时,它都会给我带来错误。你能帮我吗? 'qmake'不被识别为内部或外部命令, 可操作程序或批处理文件。 错误:[Errno 2]没有这样的文件或目录:'src/webkit_server' – Himakar

+0

@Himakar你是windows还是linux? – MYGz

+0

我在Windows 10上。 – Himakar