我正在试着从一个网站上写数据。数据在HTML中以表格的形式列出,当新的数据块在排名中列出时,标签'‘列出,标签'’代表关于排名中元素的每个描述性项目。该列表是前500台计算机的排名,列出了1-100台计算机,其中1、2、3、4等项由“”列出,计算机的每个特性以“”列出(它的存储空间、最大功率等)。
下面是我的代码:
# read the data from a URL
url = requests.get("https://www.top500.org/list/2018/06/")
url.status_code
url.content
# parse the URL using Beauriful Soup
soup = BeautifulSoup(url.content, 'html.parser')
filename = "computerRank10.csv"
f = open(filename,"w")
headers = "Rank, Site, System, Cores, RMax, RPeak, Power\n"
f.write(headers)
for record in soup.findAll('tr'):
# start building the record with an empty string
tbltxt = ""
tbltxt = tbltxt + data.text + ";"
tbltxt = tbltxt.replace('\n', ' ')
tbltxt = tbltxt.replace(',', '')
# f.write(tbltxt[0:-1] + '\n')
f.write(tbltxt + '\n')
f.close()我什么也得不到,我的CSV文件始终为空
发布于 2018-10-08 02:16:55
您应该在Python标准库上使用csv模块。
这里有一个更简单的解决方案:
import requests
import csv
from bs4 import BeautifulSoup as bs
url = requests.get("https://www.top500.org/list/2018/06")
soup = bs(url.content, 'html.parser')
filename = "computerRank10.csv"
csv_writer = csv.writer(open(filename, 'w'))
for tr in soup.find_all("tr"):
data = []
# for headers ( entered only once - the first time - )
for th in tr.find_all("th"):
data.append(th.text)
if data:
print("Inserting headers : {}".format(','.join(data)))
csv_writer.writerow(data)
continue
for td in tr.find_all("td"):
if td.a:
data.append(td.a.text.strip())
else:
data.append(td.text.strip())
if data:
print("Inserting data: {}".format(','.join(data)))
csv_writer.writerow(data)发布于 2018-10-08 02:45:07
尝试下面的脚本。它应该会获取所有数据,并将其写入csv文件:
import csv
import requests
from bs4 import BeautifulSoup
link = "https://www.top500.org/list/2018/06/?page={}"
def get_data(link):
for url in [link.format(page) for page in range(1,6)]:
res = requests.get(url)
soup = BeautifulSoup(res.text,"lxml")
for items in soup.select("table.table tr"):
td = [item.get_text(strip=True) for item in items.select("th,td")]
writer.writerow(td)
if __name__ == '__main__':
with open("tabularitem.csv","w",newline="") as infile: #if encoding issue comes up then replace with ('tabularitem.csv', 'w', newline="", encoding="utf-8")
writer = csv.writer(infile)
get_data(link)https://stackoverflow.com/questions/52690994
复制相似问题