使用美丽的汤提取

时间:2016-05-15 05:46:40

标签: python beautifulsoup

我想从网站上获取股票价格:http://www.bseindia.com/ 例如股票价格显示为“S& P BSE:25,489.57”。我想将其数字部分取为“25489.57”

这是我现在编写的代码。它正在获取此金额出现的整个div而不是金额。

以下是代码:

from bs4 import BeautifulSoup
from urllib.request import urlopen



page = "http://www.bseindia.com"

html_page = urlopen(page)

html_text = html_page.read()
soup = BeautifulSoup(html_text,"html.parser")
divtag = soup.find_all("div",{"class":"sensexquotearea"})
for oye in divtag:
    tdidTags = oye.find_all("div", {"class": "sensexvalue2"})

    for tag in tdidTags:
        tdTags = tag.find_all("div",{"class":"newsensexvaluearea"})
        for newtag in tdTags:
            tdnewtags = newtag.find_all("div",{"class":"sensextext"})
            for rakesh in tdnewtags:
                tdtdsp1 = rakesh.find_all("div",{"id":"tdsp"})
                for texts in tdtdsp1:
                    print(texts)

2 个答案:

答案 0 :(得分:6)

我浏览了当该页面加载信息时发生了什么,我能够模拟javascript在python中的作用。

我发现它引用了一个名为IndexMovers.aspx?ln=en check it out here的网页 enter image description here

看起来这个页面是以逗号分隔的事物列表。首先是名称,接下来是价格,然后是其他一些你不关心的事情。

要在python中模拟这个,我们请求页面,用逗号分隔,然后读取列表中的每个第6个值,将该值和之后的值添加到名为stockInformation的新列表中。

现在我们可以循环浏览股票信息并使用item[0]获取名称,并使用item[1]

定价
import requests

newUrl = "http://www.bseindia.com/Msource/IndexMovers.aspx?ln=en"
response = requests.get(newUrl).text
commaItems = response.split(",")


#create list of stocks, each one containing information
#index 0 is the name, index 1 is the price
#the last item is not included because for some reason it has no price info on indexMovers page
stockInformation = []
for i, item in enumerate(commaItems[:-1]):
    if i % 6 == 0:
        newList = [item, commaItems[i+1]]
        stockInformation.append(newList)


#print each item and its price from your list
for item in stockInformation:
    print(item[0], "has a price of", item[1])

打印出来:

S&P BSE SENSEX has a price of 25489.57
SENSEX#S&P BSE 100 has a price of 7944.50
BSE-100#S&P BSE 200 has a price of 3315.87
BSE-200#S&P BSE MidCap has a price of 11156.07
MIDCAP#S&P BSE SmallCap has a price of 11113.30
SMLCAP#S&P BSE 500 has a price of 10399.54
BSE-500#S&P BSE GREENEX has a price of 2234.30
GREENX#S&P BSE CARBONEX has a price of 1283.85
CARBON#S&P BSE India Infrastructure Index has a price of 152.35
INFRA#S&P BSE CPSE has a price of 1190.25
CPSE#S&P BSE IPO has a price of 3038.32
#and many more... (total of 40 items)

这显然与页面上显示的值相当 enter image description here

所以你有它,你可以准确地模拟该页面上的javascript正在做什么来加载信息。事实上,你现在拥有的信息比在页面上显示的信息更多,而且请求会更快,因为我们只下载数据,而不是所有那些无关的html。

答案 1 :(得分:3)

如果查看页面的源代码(例如将其存储到文件中并使用编辑器打开),您将看到实际股票价格25,489.57不会直接显示。价格不在存储的html代码中,而是以不同的方式加载。

您可以使用显示数字的链接页面:

http://www.bseindia.com/sensexview/indexview_new.aspx?index_Code=16&iname=BSE30

相关问题