使用Python的网页抓取数据美丽的汤 - 不能提取字段

问题描述:

我想从IG索引页使用Python美丽的汤提取股票代码(南非40)字段,但我无法检索它。使用Python的网页抓取数据美丽的汤 - 不能提取字段

我想获得的数据由是https://www.ig.com/uk/ig-indices/south-africa-40?siteId=igm

HTML代码与股票数据的网页:

<div class="ma-content title"> 
    <h1>South Africa 40</h1> 

     <p> 
      .........some text.......... 
     </p> 

</div> 

我已经试过这样:

name = soup.select('div.ma-content title h1')[0].text 

,但得到的错误信息:

Traceback (most recent call last): File "IGIndexDataScrape_Minute_v0.1.py", line 30, in name = soup.select('div.ma-content title h1')[0].text IndexError: list index out of range

以上任何建议/代码修正都会非常有帮助。

这里是直复制和粘贴完整代码:

import urllib2 
from bs4 import BeautifulSoup 

import csv 
from datetime import datetime 

from lxml import html 
import requests 

quote_page = ['https://www.ig.com/uk/ig-indices/south-africa-40?siteId=igm'] 

data = [] 
for pg in quote_page: 
page = urllib2.urlopen(pg) 

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

name = soup.select('div.ma-content title h1')[0].text 

sell_price = soup.find('span', attrs={'class':'price', 'id':'bid'}).text 
data.append(sell_price) 

buy_price = soup.find('span', attrs={'class':'price', 'id':'ofr'}).text 
data.append(buy_price) 

print sell_price + "\t\t" + buy_price + name 

# data.append(name, sell_price, buy_price) 
# print name + "\t\t" + sell_price + "\t\t" + buy_price 
+1

请编辑您的帖子并正确格式化代码:https://*.com/editing-help#code –

+0

css是错误的。它应该是'div.ma-content.title'或只是'div.title' – pguardiario

您是否尝试过find_all,而不是select?类似于:

name_div = soup.find_all('div', {'class': 'ma-content title'})[0] 
name = name_div.find('h1').text 
+0

这肯定会奏效,但我认为你忘了'}';) – hansTheFranz

+0

@hansTheFranz谢谢,我编辑了它。 :) –

+0

非常感谢你们。上述解决方案有效。 :) – manjeetss