【问题标题】:How can I use Python to scrape a multipage table and export to a CSV file?如何使用 Python 抓取多页表并导出到 CSV 文件?
【发布时间】:2020-02-23 09:06:56
【问题描述】:

我正在尝试抓取跨越多个页面的表格并导出到 csv 文件。似乎只有一行数据被导出并且混乱。

我在网上查看并尝试了许多迭代,现在非常沮丧。从代码中可以看出,我是编码新手!

import bs4 as bs
import urllib.request
import pandas as pd
import csv


max_page_num = 14
max_page_dig = 1 # number of digits in the page number


with open('result.csv',"w") as f:
    f.write("Name, Gender, State, Position, Grad, Club/HS, Rating, Commitment \n")

for i in range(0, max_page_num):  
    page_num = (max_page_dig - len(str(i))) * "0" +str(i) #gives a string in the format of 1, 01 or 001, 005 etc
    print(page_num)
    source = "https://www.topdrawersoccer.com/search/?query=&divisionId=&genderId=m&graduationYear=2020&positionId=0&playerRating=&stateId=All&pageNo=" + page_num + "&area=commitments"
    print(source)

    url = urllib.request.urlopen(source).read()    

    soup = bs.BeautifulSoup(url,'lxml')
    table = soup.find('table')
    table_rows = table.find_all('tr')

    for tr in table_rows:
        td = tr.find_all('td')
        row = [i.text for i in td]
        #final = row.strip("\n")
        #final = row.replace("\n","")
        with open('result.csv', 'a') as f:
            f.write(row)

似乎当我写入 csv 时它会覆盖以前的。它也将其粘贴在一行上,并将玩家姓名与学校名称连接起来。感谢您的所有帮助。

【问题讨论】:

    标签: python-3.x web-scraping export-to-csv multipage


    【解决方案1】:

    我认为你的内部 for 循环有问题。尝试将其重写为

    with open('result.csv', 'a') as f:
       for tr in table_rows:
          td = tr.find_all('td')
          row = [i.text for i in td]
          f.write(row)
    

    看看它是否有效。

    更一般地说,这可以通过使用 pandas 更简单地完成。尝试将您的 for 循环更改为:

    for i in range(0, max_page_num):  
       page_num = ...
       source = ....
       df = pd.read_html(source)
       df.to_csv('results.csv', header=False, index=False, mode='a') #'a' should append each table to the csv file, instead of overwriting it.
    

    【讨论】:

    • 嗨,杰克(纽约人)。非常感谢您的努力。使用您的第一种更正方法,它确实将它们全部下载,但不幸的是,它们全部与 /n 放在一条线上。第二种方法我得到错误'AttributeError:'list'对象没有属性'to_csv''。
    • @HermanL - 小世界!无论如何,df = pd.read_html(source) 可能会导致多个表,具体取决于页面 - 这就是错误所指的“列表”。要查看您捕获了多少张桌子,请添加 print(len(df))。尝试像df[0].to_csv(...)一样写入csv。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多