【问题标题】:How to get list and convert it to dataframe by web scraping in Python如何通过Python中的网络抓取获取列表并将其转换为数据框
【发布时间】:2017-06-11 12:16:23
【问题描述】:

我已经从 python 的页面中删除了数据。我能够打印表格标签的内容。但在那之后,我无法将其作为列表获取并将其转换为数据框。这是我的代码-

import urllib2
import pandas as pd
wiki = "https://www.marinetraffic.com/en/ais/index/ships/all/per_page:50/page:1"
hdr = {'User-Agent': 'Mozilla/5.0'}
req = urllib2.Request(wiki,headers=hdr)
page = urllib2.urlopen(req)
from bs4 import BeautifulSoup
soup = BeautifulSoup(page, "html.parser")
#print soup.prettify()
print soup.title.string
#print soup.a

all_links = soup.find_all("a")
for link in all_links:
     link.get("href")
all_tables=soup.find_all('table')
right_table=soup.find('table', class_='table table-hover text-left')
print right_table
#Generate lists
A=[]
B=[]
C=[]
D=[]
E=[]
F=[]
G=[]
for row in right_table.findAll("tr"):
    cells = row.findAll('td')
    states=row.findAll('img') #To store second column data
    if len(cells)==12: #Only extract table body not heading
          A.append(states[0].find(text=True))
          B.append(cells[0].find(text=True))
          C.append(cells[2].find(text=True))
          D.append(cells[3].find(text=True))
          E.append(cells[4].find(text=True))
          F.append(states[1].find(text=True))
          G.append(cells[6].find(text=True))
df=pd.DataFrame(A,columns=['Flag'])
df['Vessel ID']=B
df['MMSI']=C
df['Vessel Name']=D
df['Photo']=E
df['Type']=F
df['Latest Position']=G
print df

它只给出一个字段的数据。其余字段为空或不提供。 请帮忙。提前致谢。

编辑:我想要像this image 这样的数据 但我得到了输出like this.

【问题讨论】:

    标签: python python-2.7 web-scraping beautifulsoup


    【解决方案1】:

    我认为这就是你想要做的-

    df = pd.DataFrame([A, B, C, D, E, F, G], columns=['Flag', 'Vessel ID', 'MMSI', 'Photo', 'Type', 'Latest Position'])
    print df
    

    【讨论】:

    • 您使用此代码获得的df 的值是多少?你想要它是什么? @AshishBaboo
    • 看起来像是抓取的问题。尝试打印数组ABC,.. 并检查值是否不为空。
    • 如果我打印 right_table 。它正确显示了整个数据。所以错误是在那之后。
    • 那么ABC看起来像什么?
    • 我在生成列表时做错了一些事情。因为当我打印 A 、 B 或 C 时,它们会给我 none 或 'u\n 那是空白的。
    猜你喜欢
    • 1970-01-01
    • 2021-05-23
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    • 2020-05-04
    • 2017-11-19
    相关资源
    最近更新 更多