2017-03-25 5 views
1

私は美しいスープをPythonで使用しており、トウモロコシの商品価格のウェブスクレーピングデータを使用しています。ここではもしかしたら、データを取得する方法をサンプリングし、私のコードは次のとおりです。WSJのトウモロコシ価格を美しいスープで掻き集める

import urllib2 
import requests 
from bs4 import BeautifulSoup 
import codecs 

url="http://online.wsj.com/mdc/public/page/2_3020-cashprices-20170320.html" 
r=requests.get(url) 
soup=BeautifulSoup(r.content, "lxml") 
soup.title 
f=open('corny.txt', 'w') 
commodity = soup.findAll(attrs={"class":"text"}) 
print commodity[51] 
commo = commodity[51].string 
print commo 
#Corn, No. 2 yellow. Cent. Ill. bu-BP,U (success!!) 
f.write(commo) 
corndate = soup.findAll("span") 
print corndate[16] 
cdate = corndate[16].string 
print cdate 
f.write(cdate) 
price = soup.findAll("b") 
print price[46] 
pricey = price[46].string 
print pricey 
f.write(pricey) 
f.close() 

は、問題は、私は2005年から現在までの毎日のためにこれを行う必要があるということですが、タグの順序が変わるので、私はできません同じコードを維持してください(例えば、1日のうちに51番目のattrs = {"class": "text"}はコーンですが、1週間後にはコットンのようなものです。 CORN ONLYの日付と価格(水価格)(トウモロコシ、第2の黄色。セント。イリノイ州BU-BP、U)。

はまた、URLの構造は、私が理解することができますよりも、より複雑なようだ。

答えて

0

抽出trタグで検索し、文字列"Corn, No. 2 yellow"を含む要素を検索します。その後、そこから価格を入手してください。

url="http://online.wsj.com/mdc/public/page/2_3020-cashprices-20170320.html" 
r=requests.get(url) 
soup=BeautifulSoup(r.content, "lxml") 


corndate = soup.find_all("span") 
cdate = corndate[16].string 
print (cdate) 

corn_name = "" 
corn_price = "" 

corn_info = soup.find_all("tr") 
for corn in corn_info: 
    text = corn.get_text() 
    if(text.find("Corn, No. 2 yellow") > -1): 
     text = text.replace("\n\n", "\n", 10) 
     text = text.strip("\n") 
     all_text = text.split("\n") 
     corn_name = all_text[0] 
     corn_price = all_text[3] 
     break 

file = open("Corn Info.txt", "a") 
file.write(corn_name + "\n") 
file.write(corndate + "\n") 
file.write(corn_price + "\n") 
file.close() 
+0

これをテキストファイルに別のURLで何度も印刷するにはどうすればよいですか? –

+0

あなたのテキストファイルに書いたのとまったく同じです。コードを更新していますが、ちょっと待ってください。 –

+0

@SierraThomander異なる日付の異なるテキストファイルを作成しますか? –

関連する問題