【问题标题】:Web scraping data using Python Beautiful Soup - can't extract field使用 Python Beautiful Soup 抓取网络数据 - 无法提取字段
【发布时间】:2017-12-21 02:14:41
【问题描述】:

我正在尝试使用 Python Beautiful Soup 从 IG 索引页面中提取股票代码(南非 40)字段,但我无法检索它。

我试图从中获取数据的网页是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(最近一次调用最后一次):文件 “IGIndexDataScrape_Minute_v0.1.py”,第 30 行,在 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

【问题讨论】:

标签: python web web-scraping beautifulsoup


【解决方案1】:

您是否尝试过find_all 而不是select?比如:

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

【讨论】:

  • 这肯定会起作用,但我想你忘了} ;)
  • 非常感谢大家。上述解决方案有效。 :)
  • @manjeetss 我什么都没做,感谢 Sam。很高兴它仍然有效,快乐刮:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
  • 2015-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多