如何使用R或Python使用多页刮取web表

如何使用R或Python使用多页刮取web表,python,r,web,scrape,Python,R,Web,Scrape,我想创建一个web来收集数据,以便研究数据挖掘。此web数据包含一个包含43页的大表。它还将一些股票隐藏在扩展菜单的最右侧 网页如下 基于和的解决方案: 为了便于访问,我将所有数据放入字典列表中。您可以修改代码以直接写入CSV或任何内容,现在您做了什么?有代码吗?@yan9yu,我用XML和Curl试过R。因为我在R方面比Python强。但我还是不知道怎么刮桌子。我会在你尝试的同时更新我的代码。@yan9yu,你好,你能帮我一下吗,谢谢!您只需要第一页上的数据,还是所有页面上的数据?只有“当

我想创建一个web来收集数据,以便研究数据挖掘。此web数据包含一个包含43页的大表。它还将一些股票隐藏在扩展菜单的最右侧

网页如下

基于和的解决方案:


为了便于访问,我将所有数据放入字典列表中。您可以修改代码以直接写入CSV或任何内容,现在您做了什么?有代码吗?@yan9yu,我用XML和Curl试过R。因为我在R方面比Python强。但我还是不知道怎么刮桌子。我会在你尝试的同时更新我的代码。@yan9yu,你好,你能帮我一下吗,谢谢!您只需要第一页上的数据,还是所有页面上的数据?只有“当日", 或两者兼而有之”当日“和”当月“?非首页上的数据通过ajax@ZZY,我希望数据带有“当月,以及所有43页的数据。谢谢!!,我刚刚更新了上面的代码。我运行了你的代码,你的代码与我想要的不完全一样,只是当月“。你能运行我的代码以便理解我想要的内容吗?谢谢!正如我所看到的,区别在于你使用的是”“。该URL只能在第一页上给你记录,不是吗?那么你已经解决了你的问题了吗?几乎,我的意思是,你能添加代码将.to csv写入桌面吗?你可以参考
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
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)