2017-02-12 5 views
2

Pythonに数ヶ月、BeautifulSoupを使用してテーブルから情報を取り出すのに問題があります。私はエラーコードを取得していませんが、代わりにテーブルからデータを受け取っていません。テーブルから情報を得ることができない美しいスープ

import bs4 as bs 
import requests 

resp = requests.get('https://www.thestreet.com/markets/gainers.html') 
soup = bs.BeautifulSoup(resp.text, "lxml") 
table = soup.find('table', {'id': 'nyseData'}) 

tickers = [] 
for row in table.findAll('tr')[1:]: 
    ticker = row.findAll('td')[1].text 
    tickers.append(ticker) 

ご協力いただきありがとうございます。

答えて

1

特定のユーザーエージェントが自分のサイトにアクセスできないという問題がページで発生しています。これは、requestsヘッダーにユーザーエージェント文字列を設定することで修正できます。

は、ユーザーエージェントとのあなたのコードが追加さ:

import bs4 as bs 
import requests 

headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'} 

resp = requests.get('https://www.thestreet.com/markets/gainers.html', headers=headers) 
soup = bs.BeautifulSoup(resp.text,'lxml') 
table = soup.find('table', {'id': 'nyseData'}) 

tickers = [] 
for row in table.findAll('tr')[1:]: 
    ticker = row.findAll('td')[1].text 
    tickers.append(ticker) 

print tickers 

出力:

[u'QUOT', u'BCEI', u'ATEN', u'SKX', u'FBK', u'FBM', u'CGI', u'SDRL', u'ELLI', u'CELP', u'SXCP', u'CUB', u'GLF', u'SID', u'HBM', u'NE', u'CBG', u'PJT', u'VVI', u'ARL'] 
関連する問題