美丽的汤/请求没有取值

时间:2018-04-09 17:39:07

标签: python html beautifulsoup python-requests

目标:获取在此website

上定期更新的值

网站上想要的值/数字是这样的:

Advances -  1089    Declines -  708 Unchanged - 80  Total - 1877

我使用requestsBeautifulSoup来阅读html并获取这些数字。但有一个问题。当我在网络浏览器中打开页面并“检查元素”时我明白了:

<td style="border-right: 1px solid #ACA99F;width:82px;color:green;font-size:1.2em;">1089</td>

您会看到该行包含我想要的数据,即>1089<。但是当我运行我的python时,抓取代码requests不会返回这些数字。相反,我得到了>-<

<tr>
<td>Advances - </td>
<td style="border-right: 1px solid 
#ACA99F;width:82px;color:green;font-size:1.2em;">-</td>
<td style="padding-left:8px;">Declines - </td>
<td style="border-right: 1px solid #ACA99F;width:82px;color:red;font-
size:1.2em;">-</td>
<td style="padding-left:8px">Unchanged - </td>
<td style="border-right: 1px solid #ACA99F;width:82px;font-
size:1.2em;">-</td>
<td style="padding-left:8px">Total - </td> 
<td style="width:82px;text-align:right;font-size:1.2em;">-</td>
</tr>
</table>]

我执行的代码是:

import requests
from bs4 import BeautifulSoup

Base_url = 
("https://www.nseindia.com/live_market/dynaContent/live_market.htm")

page = requests.get(Base_url)
page.status_code
page.content

soup = BeautifulSoup(page.content, 'html.parser')

ti=soup.find_all(class_= "mkt_content")
tc=soup.find_all(id = "advanceDecline")

print(tc)

发生了什么错误以及在哪里。我认为问题出现在requests而不是Beautiful Soup。请详细说明,因为这是我第一次使用HTML /抓取。如果需要任何其他信息,请在我将提供的评论中提问。

3 个答案:

答案 0 :(得分:0)

这是因为内容是通过JavaScript动态生成的。但是,您可以通过以下方式查询其API来获取这些值:

import requests
import json


URL = "https://www.nseindia.com/live_market/dynaContent/live_analysis/changePercentage.json"

with requests.session() as s:
    s.headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0'}
    resp = s.get(URL).json()
    if resp['success']:
        print(resp['rows'][0]['advances'])
        print(resp['rows'][0]['declines'])
        print(resp['rows'][0]['unchanged'])
        print(resp['rows'][0]['total'])

<强>输出:

1089
708
80
1877

答案 1 :(得分:0)

您可以使用selenium更好地模拟浏览器:

from selenium import webdriver
from bs4 import BeautifulSoup as soup
d = webdriver.Chrome()
d.get('https://www.nseindia.com/live_market/dynaContent/live_market.htm')
#now, inspection of the source shows the correct values are listed
s = ' '.join([i.text for i in soup(d.page_source, 'lxml').find_all('td')][:8])

输出:

u'Advances -  1089 Declines -  708 Unchanged -  80 Total -  1877'

答案 2 :(得分:0)

另一种解决方案是使用Requests-HTML

<强>代码:

from requests_html import HTMLSession

session = HTMLSession()
r = session.get('https://www.nseindia.com/live_market/dynaContent/live_market.htm')
r.html.render()
result = r.html.find('#advanceDecline', first=True).text.replace('\n', ' ')
print(result)

输出:

Advances - 1089 Declines - 708 Unchanged - 80 Total - 1877