【问题标题】:Error "6 columns passed, passed data had 286 columns "错误“通过了 6 列,传递的数据有 286 列”
【发布时间】:2021-08-20 23:34:42
【问题描述】:

我正在对本网站上的表格进行网络抓取:“https://www.privatefly.com/privatejet-services/private-jet-empty-legs.html

一切都很好,但“价格”标签有一个小问题,无法修复。过去几个小时我一直在尝试,这是我遇到的最后一个错误:“https://www.privatefly.com/privatejet-services/private-jet-empty-legs.html

from selenium import webdriver
from bs4 import BeautifulSoup
import pandas as pd

import requests
page = requests.get("https://www.privatefly.com/privatejet-services/private-jet-empty-legs.html")

soup = BeautifulSoup(page.content, "lxml")
gdp = soup.find_all("table", attrs={"class": "table flight-detail hidden-xs"})
print("Number of tables on site: ",len(gdp))

table1 = gdp[0]
# the head will form our column names
body = table1.find_all("tr")
print(len(body))
# Head values (Column names) are the first items of the body list
head = body[0] # 0th item is the header row
body_rows = body[1:] # All other items becomes the rest of the rows

# Lets now iterate through the head HTML code and make list of clean headings

# Declare empty list to keep Columns names
headings = []
for item in head.find_all("th"): # loop through all th elements
    # convert the th elements to text and strip "\n"
    item = (item.text).rstrip("\n")
    # append the clean column name to headings
    headings.append(item)
print(headings)

import re
all_rows = [] # will be a list for list for all rows
for row_num in range(len(body_rows)): # A row at a time
    row = [] # this will old entries for one row
    for row_item in body_rows[row_num].find_all("td")[:-1]: #loop through all row entries
        # row_item.text removes the tags from the entries
        # the following regex is to remove \xa0 and \n and comma from row_item.text
        # xa0 encodes the flag, \n is the newline and comma separates thousands in numbers
        aa = re.sub("(\xa0)|(\n)|(\t),","",row_item.text)
        #append aa to row - note one row entry is being appended
        row.append(aa)
    # append one row to all_rows
    all_rows.append(row)
    for row_item in body_rows[row_num].find_all("td")[-1].find("span").text: #loop through the last row entry, price.
        aa = re.sub("(\xa0)|(\n)|(\t),","",row_item)
        row.append(aa)
    all_rows.append(row)

# We can now use the data on all_rowsa and headings to make a table
# all_rows becomes our data and headings the column names
df = pd.DataFrame(data=all_rows,columns=headings)
#df.head()
#print(df)
df["Date"]=pd.to_datetime(df["Date"]).dt.strftime("%d/%m/%Y")
print(df)

如果您可以运行代码并告诉我如何解决此问题,以便我可以在使用“ print(df)”时打印所有内容。 以前,我可以打印除价格之外的所有内容,而价格却是“\t\t\t\t\t\t\t”而不是价格。 谢谢。

【问题讨论】:

    标签: python dataframe machine-learning web-scraping jupyter-notebook


    【解决方案1】:

    要将表格放入panda DataFrame,可以使用以下示例:

    import requests
    import pandas as pd
    from bs4 import BeautifulSoup
    
    
    url = (
        "https://www.privatefly.com/privatejet-services/private-jet-empty-legs.html"
    )
    
    soup = BeautifulSoup(requests.get(url).content, "html.parser")
    
    data = []
    for tr in soup.select("tr:has(td)"):
        row = [td.get_text(strip=True, separator=" ") for td in tr.select("td")]
        data.append(row)
    
    df = pd.DataFrame(data, columns="From To Aircraft Seats Date Price".split())
    print(df)
    df.to_csv("data.csv", index=False)
    

    打印:

                                               From                                                 To                       Aircraft Seats                          Date                          Price
    0                   Prague Vaclav Havel Airport                            Bratislava M R Stefanik                  Citation XLS+     9  Thu Jun 03 00:00:00 UTC 2021            €3 300 (RRP €6 130)
    1                                       Billund                                             Odense              Learjet 45 / 45XR     8  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €7 100)
    2                       La Roche/yon Les Ajoncs                                  Nantes Atlantique             Embraer Phenom 100     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €4 820)
    3                            London Biggin Hill                                   Paris Le Bourget             Cessna 510 Mustang     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €6 980)
    4                   Prague Vaclav Havel Airport                                  Salzburg (mozart)                Gulfstream G200     9  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €8 800)
    5                             Palma De Mallorca                                          Edinburgh       Cessna C525 Citation CJ2     5  Thu Jun 03 00:00:00 UTC 2021   Call for Price (RRP €18 680)
    6                         Linz Blue Danube Linz                                     Munich Munchen             Cessna 510 Mustang     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €3 600)
    7                               Geneva Cointrin                                   Paris Le Bourget             Cessna 510 Mustang     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €9 240)
    8                              Vienna Schwechat                             Cologne-bonn Koln Bonn             Cessna 510 Mustang     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €8 590)
    9                              Cannes Mandelieu                                    Geneva Cointrin             Cessna 510 Mustang     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €8 220)
    10                            Brussels National                             Cologne-bonn Koln Bonn             Cessna 510 Mustang     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €3 790)
    11                                        Split                                        Bari Palese             Cessna 510 Mustang     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €8 220)
    12                          Copenhagen Roskilde                                            Aalborg                 Challenger 604    11  Thu Jun 03 00:00:00 UTC 2021   Call for Price (RRP €16 750)
    13                            Brussels National                                      Leipzig Halle             Cessna 510 Mustang     4  Thu Jun 03 00:00:00 UTC 2021    Call for Price (RRP €6 690)
    
    ...
    

    并保存data.csv(来自 LibreOffice 的屏幕截图):

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 2019-05-11
      • 1970-01-01
      相关资源
      最近更新 更多