2014-11-04 3 views
0

데이터 마이닝을위한 데이터를 수집하기 위해 웹을 긁어 내고 싶습니다. 이 웹 데이터에는 43 페이지가있는 큰 테이블이 있습니다. 또한 확장 메뉴의 가장 오른쪽에있는 일부 주식을 숨 깁니다.R 또는 파이썬을 사용하여 여러 페이지로 웹 테이블을 긁는 방법

enter image description here

이 웹 페이지는 다음과 같습니다.

http://data.10jqka.com.cn/market/longhu/yyb/

import bs4 
import requests 


url = r"http://data.10jqka.com.cn/market/longhu/yyb/" 

response = requests.get(url) 
if response.status_code == 200: 
    content = response.content 

soup = bs4.BeautifulSoup(content) 
table_results = soup.findAll("table", {"class": "m_table"}) 
for item in table_results: 
    company_name = item.findAll("td", {"class": "tl"})[0].text.strip() 
    detail = item.findAll("td", {"class": "tc"})[0].text.strip() 
    c_rise = item.findAll("td", {"class": "c_rise"})[0].text.strip() 
    c_fall = item.findAll("td", {"class": "c_fall"})[0].text.strip() 
    cur = item.findAll("td", {"class": "cur"})[0].text.strip() 
    lhb_stocklist = item.findAll("div", {"class": "lhb_stocklist"})[0].text.strip() 
    print company_name, detail, c_rise, c_fall, lhb_stocklist 
+0

지금 무엇을 했습니까? 어떤 코드? – Eric

+0

@ yan9yu, 나는 XML과 Curl로 R을 시도했다. Rcause에서는 R보다 더 강합니다. 그러나 나는 아직도이 테이블을 긁는 법을 모른다. 시도하면서 동시에 코드를 업데이트 할 것입니다. –

+0

@ yan9yu 안녕하세요, 제게 손을 줘 주셔서 감사합니다! –

답변

0

requests, BeautifulSoup 기반으로하는 솔루션 및 lxml는 :

import json 
import requests 
from bs4 import BeautifulSoup 

URL = 'http://data.10jqka.com.cn/interface/market/longhuyyb/stocknum/desc/%d/20' 
# config end_page as needed, or parse http://data.10jqka.com.cn/market/longhu/yyb/ to make it auto adapted 
end_page = 2 

result = [] 
for page_idx in range(1, end_page + 1): 
    print 'Extracting page', page_idx 
    raw_response = requests.get(URL % page_idx) 
    page_content = json.loads(raw_response.text)['data'] 
    html = BeautifulSoup(page_content, 'lxml') 
    for row in html.tbody.find_all('tr'): 
     company = row.find(class_='tl').text 
     detail_link = row.find(class_='tl').a['href'] 
     buy = float(row.find(class_='c_rise').text) 
     sell = float(row.find(class_='c_fall').text) 
     stock_cnt = int(row.find(class_='cur').text) 
     stocks = [] 
     for a in row.find(class_='lhb_stocklist_box hide').p.find_all('a'): 
      stocks.append((a.text, a['href'])) 
     result.append({ 
      'company': company, 
      'detail_link': detail_link, 
      'buy': buy, 
      'sell': sell, 
      'stock_cnt': stock_cnt, 
      'stocks': stocks, 
     }) 

print 'Company number:', len(result) 

나는 쉽게 액세스하기위한, 사전의 목록에 모든 데이터를 넣어. CSV 또는 무엇이든 직접 작성하도록 코드를 수정할 수 있습니다.

+0

, 방금 위의 코드를 업데이트했습니다. 귀하의 코드를 실행하고 귀하의 코드가 정확히 내가 원하는 당연히 제외하고 싶지 않습니다. 내 코드를 실행하여 원하는 것을 이해할 수 있습니까? 감사! –

+0

내가 본 것처럼 차이점은 "http://data.10jqka.com.cn/market/longhu/yyb/"를 사용하고 있다는 것입니다. 그 URL은 첫 페이지에만 기록을 남길 수 있습니다. 그렇죠? 이미 문제를 해결하셨습니까? – ZZY

+0

거의, 내 말은, 코드를 데스크탑에 write.to csv에 추가 할 수 있습니까? –