【问题标题】:Scraping data from a website using Python 2使用 Python 2 从网站抓取数据
【发布时间】:2017-06-04 20:49:45
【问题描述】:

我正在尝试从股市中抓取数据,但在打印数据时却一无所获。我要苹果的价格。

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

【问题讨论】:

    标签: python web web-scraping


    【解决方案1】:

    您能否详细说明您要从页面中提取的具体内容?我可以使用下面的代码提取您的标签(注意:使用 Python 3、BeautifulSoup 和 requests,我推荐所有这些都用于网络抓取;还要找出您需要为 headers 变量添加的内容,我建议:@987654321 @)

    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)
    

    【讨论】:

    • 我正在寻找苹果的价格,每次运行代码时它都会返回一个空列表
    • 我建议您在此处查看这些答案:stackoverflow.com/questions/20045955/… K DawG 的答案解释了正则表达式如何捕获 标签在您的情况下,您需要 <span> 标签,它应该给您所有跨度标签的列表,可以进一步搜索以找到您想要的信息。</span>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多