【问题标题】:Scrape Data from Yahoo finance headline从雅虎财经头条抓取数据
【发布时间】:2017-04-03 08:54:41
【问题描述】:

我在这个网站上进行了一些研究以找到解决我的问题的方法,但要么线程太旧(Yahoo 几年前刷新了它的页面),要么它们太复杂(我仍然 新刮)。 我想在此代码创建的 csv 文件中搜索关键字。

我使用了这段代码,但是雅虎的标题有点难以获得,让我解释一下。

# import libraries
import urllib2  
from bs4 import BeautifulSoup  
import csv  
from datetime import datetime

quote_page = 'https://finance.yahoo.com/' 
page = urllib2.urlopen(quote_page)  
soup = BeautifulSoup(page, 'html.parser') 
name_box = soup.find('h1', attrs={'class': 'name'})
name = name_box.text.strip() 
print name


with open('index.csv', 'a') as csv_file:  
writer = csv.writer(csv_file)
writer.writerow([name, ])

正如您在这张图片中看到的,标题介于以下之间: !-- 反应文本:3388 --> !-- /反应文本--> 但我不知道如何转换我的代码以便能够阅读这些。

解决方案可能很简单,但我尝试了很多方法,但似乎没有任何效果。

我希望您能帮助我或找到另一种在这些标题中查找关键字的方法。

提前非常感谢您。

【问题讨论】:

  • 您是否尝试为 StretchedBox 上方的锚标记选择 innerText?

标签: python web-scraping yahoo-finance


【解决方案1】:

我使用了requests 而不是urllib2。据我所知,这是更多人使用的。

至于标题:

import requests
from bs4 import BeautifulSoup
a = requests.get('https://finance.yahoo.com/m/8bb0b8f6-9b97-32df-8f56-31690cd85cea/long-lines-are-killing.html')
soup = BeautifulSoup(a.content, 'lxml')
search = soup.find_all('h1', {'class':'Lh(36px) Fz(25px)--sm Fz(32px) Mb(17px)--sm Mb(20px) Mb(30px)--lg Ff($ff-primary) Lts($lspacing-md) Fw($fweight) Fsm($fsmoothing) Fsmw($fsmoothing) Fsmm($fsmoothing) Wow(bw)'})
print(search[0].text) # prints Long Lines Are Killing Starbucks, So Here's Its Bold New Solution to the Major Problem

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 2020-09-10
    • 1970-01-01
    • 2017-01-14
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多