Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Webscraping问题,其中dataframe到csv将输出放在一个单元格中_Python_Python 3.x_Dataframe_Web Scraping - Fatal编程技术网

Python Webscraping问题,其中dataframe到csv将输出放在一个单元格中

Python Webscraping问题,其中dataframe到csv将输出放在一个单元格中,python,python-3.x,dataframe,web-scraping,Python,Python 3.x,Dataframe,Web Scraping,我正在努力帮助我们的足球教练,他正在做一些帮助贫困儿童被招募的工作。我正试图刮一个“顶级抽屉”的网页,这样我们就可以跟踪玩家的位置。我根本不是一个python专家,我的头撞在墙上。我昨天得到了一些帮助,并尝试实现-请参阅下面的两组代码。两者都没有将数据放入一个好的表格中,我们可以进行排序和分析等。提前感谢您的帮助 import bs4 as bs import urllib.request import pandas as pd import csv max_page_num = 14 ma

我正在努力帮助我们的足球教练,他正在做一些帮助贫困儿童被招募的工作。我正试图刮一个“顶级抽屉”的网页,这样我们就可以跟踪玩家的位置。我根本不是一个python专家,我的头撞在墙上。我昨天得到了一些帮助,并尝试实现-请参阅下面的两组代码。两者都没有将数据放入一个好的表格中,我们可以进行排序和分析等。提前感谢您的帮助

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", newline='') 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
   source = "https://www.topdrawersoccer.com/search/?query=&divisionId=&genderId=m&graduationYear=2020&positionId=0&playerRating=&stateId=All&pageNo=" + page_num + "&area=commitments"
   df = pd.read_html(source)
   df = pd.DataFrame(df)
   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分隔符等将输出混成一行

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", newline='') 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 = soup.table
    table_rows = table.find_all('tr')

    with open('result.csv', 'a', newline='') as f:
       for tr in table_rows:
           td = tr.find_all('td')
           row = [i.text for i in td]
           f.write(str(row))
在第一个版本中,数据都放在一行上,没有分开。 第二个版本将每个页面放在一个单元格中,并将页面一分为二。

页面可能有许多HTML格式的
(有时用于创建菜单或组织页面上的元素)和
pandas.read\u HTML()
为页面上的每个
创建
数据帧,它总是返回包含所有创建的
数据帧的列表(即使只有一个
),您必须检查哪一个包含您的数据。您可以显示列表中的每个
数据帧
,以查看需要哪一个。这样,我知道第一个数据帧包含您的数据,您必须使用
[0]
来获取它

import pandas as pd

max_page_num = 15 # it has to be 15 instead of 14 because `range(15)` will give `0-14`

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

for i in range(max_page_num):  
   print('page:', i)

   page_num = str(i)
   source = "https://www.topdrawersoccer.com/search/?query=&divisionId=&genderId=m&graduationYear=2020&positionId=0&playerRating=&stateId=All&pageNo=" + page_num + "&area=commitments"

   all_tables = pd.read_html(source)
   df = all_tables[0]
   print('items:', len(df))

   df.to_csv('results.csv', header=False, index=False, mode='a') #'a' should append each table to the csv file, instead of overwriting it.

编辑:

在第二个版本中,您应该使用
strip()
删除csv将作为新行开头的
\n

您不应该使用
str(row)
,因为它使用
[]
创建字符串,这在csv文件中是不正确的。您应该使用
“,”.join(row)
来创建字符串。您必须在每行末尾添加
\n
,因为
write()
不会添加它

但是最好使用
csv
模块及其
writerow()
来实现这一点。它会将列表转换为字符串,使用
作为分隔符,并自动添加
\n
。如果某个项目将包含
\n
,则它将把它放在
中以创建正确的行

import bs4 as bs
import urllib.request
import csv


max_page_num = 15


fh = open('result.csv', "w", newline='')
csv_writer = csv.writer(fh)

csv_writer.writerow( ["Name", "Gender", "State", "Position", "Grad", "Club/HS", "Rating", "Commitment"] )

for i in range(max_page_num):
    print('page:', i)

    page_num = str(i)
    source = "https://www.topdrawersoccer.com/search/?query=&divisionId=&genderId=m&graduationYear=2020&positionId=0&playerRating=&stateId=All&pageNo=" + page_num + "&area=commitments"

    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.strip() for i in td] # strip to remove spaces and '\n'
        row = [i.get_text(strip=True) for i in td] # strip to remove spaces and '\n'
        if row: # check if row is not empty
            #print(row)
            csv_writer.writerow(row)

fh.close()        

因为页面可能有许多
,所以
pd.read\u html
从不返回一个
DataFrame
,而是列出许多
DataFrames
,您必须检查哪个页面有您的数据,然后使用它。但首先您必须检查paga是否没有使用JavaScript创建表
pandas
BeautifulSoup
无法运行JavaScript。使用
str(行)
创建字符串时使用的
[]
在csv文件中不正确。您应该使用
“,”.join(row)
来创建正确的字符串。不要忘记在末尾添加
\n
,因为
write()
不会添加
\n
。但是最好使用
csv
writerow()
,这可以解决其他数据问题,比如文本中的
。太棒了!我还在学习,所以这非常有帮助,节省了我很多时间。非常感谢