2017-03-25 1 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 년부터 매일이 작업을 수행해야하지만 태그 변경의 순서이다, 그래서 나는 할 수 없습니다 같은 코드를 유지하십시오 (예를 들어 하루 동안 51 번째 attrs = { "class": "text"}는 옥수수에 대한 것이지만 일주일 후에는 면화 같은 것입니다.) 텍스트 파일 출력 옥수수의 날짜와 가격 (수 가격) 만 (옥수수, 제 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 다른 날짜에 대해 다른 텍스트 파일을 만들고 싶습니까? –