在冠层上使用Python进行Web刮擦

时间:2016-09-16 02:46:00

标签: python web-scraping canopy

我在这行代码中遇到问题,我想在其中列出所列公司的4种股票价格。我的问题是,虽然我运行它时没有错误,但代码只打印出股票价格应该去的空括号。这是我困惑的根源。

import urllib2
import re

symbolslist = ["aapl","spy","goog","nflx"]
i = 0

while i<len(symbolslist):
    url = "http://money.cnn.com/quote/quote.html?symb=' +symbolslist[i] + '"
    htmlfile = urllib2.urlopen(url)
    htmltext = htmlfile.read()
    regex = '<span stream='+symbolslist[i]+' streamformat="ToHundredth" streamfeed="SunGard">(.+?)</span>'
    pattern = re.compile(regex)
    price = re.findall(pattern,htmltext)
    print "the price of", symbolslist[i], " is ", price
    i+=1

1 个答案:

答案 0 :(得分:1)

因为你没有传递变量:

 url = "http://money.cnn.com/quote/quote.html?symb=' +symbolslist[i] + '"
                                                         ^^^^^
                                                      a string not the list element

使用 str.format

url = "http://money.cnn.com/quote/quote.html?symb={}".format(symbolslist[i])

你也可以直接在列表上迭代,不需要while循环,从不parse html with a regex,使用像bs4这样的html解析,你的正则表达式也是错误的。没有stream="aapl"等。您想要的是streamformat="ToHundredth"streamfeed="SunGard";

的范围
import urllib2
from bs4 import BeautifulSoup

symbolslist = ["aapl","spy","goog","nflx"]


for symbol in symbolslist:
    url = "http://money.cnn.com/quote/quote.html?symb={}".format(symbol)
    htmlfile = urllib2.urlopen(url)
    soup = BeautifulSoup(htmlfile.read())
    price = soup.find("span",streamformat="ToHundredth", streamfeed="SunGard").text
    print "the price of {} is {}".format(symbol,price)

您可以查看我们是否运行了代码:

In [1]: import urllib2

In [2]: from bs4 import BeautifulSoup

In [3]: symbols_list = ["aapl", "spy", "goog", "nflx"]

In [4]: for symbol in symbols_list:
   ...:         url = "http://money.cnn.com/quote/quote.html?symb={}".format(symbol)
   ...:         htmlfile = urllib2.urlopen(url)
   ...:         soup = BeautifulSoup(htmlfile.read(), "html.parser")
   ...:         price = soup.find("span",streamformat="ToHundredth", streamfeed="SunGard").text
   ...:         print "the price of {} is {}".format(symbol,price)
   ...:     
the price of aapl is 115.57
the price of spy is 215.28
the price of goog is 771.76
the price of nflx is 97.34

我们得到你想要的东西。