使用Python 2从网站上刮取数据

时间:2017-01-20 00:03:13

标签: python web web-scraping

我正在试图从股票市场中获取数据,但是当我打印出数据时,我一直没有得到任何结果。我想要苹果的价格。

import urllib
import re



htmlfile = urllib.urlopen("http://finance.yahoo.com/q?s=AAPL&q1=1")

htmltext = htmlfile.read()

regex = '<span class="Fw(b) Fz(36px) Mb(-4px)" data-reactid="270">(.+?)</span>'

pattern = re.compile(regex)

price = re.findall(pattern,htmltext)

print price

1 个答案:

答案 0 :(得分:0)

你能详细说明你究竟想从页面中提取什么内容吗?我能够使用下面的代码拉出你的标签(注意:使用Python 3,BeautifulSoup和请求,我建议用于网页抓取;还要找出你需要为header变量添加的内容,我建议:{{ 3}})

import requests
from bs4 import BeautifulSoup

url = 'http://finance.yahoo.com/q?s=AAPL&q1=1'

headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.3; .NET4.0C; .NET4.0E; rv:11.0) like Gecko'}

r = requests.get(url, headers=headers)

soup = BeautifulSoup(r.text, "html.parser")

for item in soup.find_all('span', {"class":"Fw(500) Pstart(10px) Fz(24px) C($dataRed)"}):
    print(item)