使用BeautifulSoup刮取数据,却没有得到所有的行。

问题描述 投票:0回答:1

我是Python和一般的编码新手。我有95%的经验,而我建立的代码只能从Wikipedia中检索出表格的第一行。看起来我缺少了一些微不足道的东西。我也想请大家帮忙。请看下面的代码。

from bs4 import BeautifulSoup
import requests
import pandas as pd

    URL_TO = 'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M'
    response = requests.get(URL_TO)
    soup = BeautifulSoup(response.text,'html.parser')
    soup.prettify()

    table = soup.find('table', {'class': 'wikitable sortable'}).tbody

    rows = table.find_all('tr')

    columns = [v.text.replace('\n', '') for v in rows[0].find_all('th')]

    df = pd.DataFrame(columns = columns)

    for i in range(1, len(rows)):
        tds = rows[i].find_all('td')

        if len(tds) ==3:
            values= [tds[0].text.replace('\n',''), tds[1].text.replace('\n',''), tds[2].text.replace('\n','')]
        else:
            values = [td.text.replace('\n','') for td in tds]

    df = df.append(pd.Series(values, index=columns), ignore_index=True)

    df.head()
pandas web-scraping beautifulsoup rows
1个回答
0
投票

你需要包括 df.append() 在你迭代的行内。目前它通过你的迭代放不追加它。

其他一些事情。

  1. 由于你是在一个列表中迭代,你不需要创建arange和使用索引。只要使用 for row in rows:
  2. 而不是替换为 '\n',您可以使用 .strip() 去掉任何白色的空间。它将会照顾到这一点,和任何填充的空间。
  3. 为什么是 "如果 tds == 3: else: 语句?不需要
  4. 因为这是一个 <table> 标签,与大熊猫一起走。.read_html(). 它为你做了所有这些工作(使用BeautifulSoup的引擎盖)。请看下面的代码

所以这里是为你的代码做的编辑。再一次,唯一需要修改的是对 df.append

from bs4 import BeautifulSoup
import requests
import pandas as pd

URL_TO = 'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M'
response = requests.get(URL_TO)
soup = BeautifulSoup(response.text,'html.parser')
soup.prettify()

table = soup.find('table', {'class': 'wikitable sortable'}).tbody

rows = table.find_all('tr')

columns = [v.text.strip() for v in rows[0].find_all('th')]

df = pd.DataFrame(columns = columns)

for row in rows:
    if row.find_all('td'):
        tds = row.find_all('td')
        values = [td.text.strip() for td in tds]
        df = df.append(pd.Series(values, index=columns), ignore_index=True)

同样的结果,使用PANDAS。

import pandas as pd

url = 'https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_M'
df = pd.read_html(url)[0]
© www.soinside.com 2019 - 2024. All rights reserved.