【问题标题】:How can I automatically parse tables spanning over multiple pages with Python如何使用 Python 自动解析跨越多个页面的表
【发布时间】:2017-11-09 21:09:44
【问题描述】:

我想解析跨越多个页面的表(或多个表)。 我在下面这样做的方式可行,但是太手动了,我希望它能够自动解析来自不同页面的表格并将它们组合成一个。页数可能并不总是相同。

from urllib.request import urlopen
from bs4 import BeautifulSoup
import pandas as pd

one = "https://rittresultater.no/nb/sb_tid/923?page=0&pv2=11027&pv1=U"
two = "https://rittresultater.no/nb/sb_tid/923?page=1&pv2=11027&pv1=U"
three = "https://rittresultater.no/nb/sb_tid/923?page=2&pv2=11027&pv1=U"

#parse the first page
html = urlopen(one)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
one = pd.read_html(str(table))[0]

#parse the second page
html = urlopen(two)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
two = pd.read_html(str(table))[0]

#parse thr third page
html = urlopen(three)
soup = BeautifulSoup(html, "lxml")
table = soup.find_all(class_="table-condensed")
three = pd.read_html(str(table))[0]

df = pd.concat([one,two,three], axis = 0)
df

请注意,网址仅在“page=X”中有所不同。网页本身也包含指向例如的链接。下一页。

【问题讨论】:

    标签: python-3.x parsing beautifulsoup html-table threadpool


    【解决方案1】:
    results = {}
    for page_num in range(1, 10): #change depending on max page
        address = 'https://rittresultater.no/nb/sb_tid/923?page=' + \
                   str(page_num) + '&pv2=11027&pv1=U' 
    
        html = urlopen(address)
        soup = BeautifulSoup(html, 'lxml')
        table = soup.find_all(class='table-condensed')
        output = pd.read_html(str(table))[0]
        results[page_num] = output
    

    当它完成后,使用列表推导来做相关的事情来输出,如果它是你代码中的最后一行但按比例放大,请执行以下操作:

    df = pd.concat([v for v in results.values()], axis = 0)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2011-04-26
      相关资源
      最近更新 更多