[英]Beautiful Soup Scraping table
我有這小段代碼可以從網站上抓取表格數據,然后以csv格式顯示。 問題是for循環多次打印記錄。 我不確定是否是由於
標簽。 順便說一句,我是Python的新手。 謝謝你的幫助!
#import needed libraries
import urllib
from bs4 import BeautifulSoup
import requests
import pandas as pd
import csv
import sys
import re
# read the data from a URL
url = requests.get("https://www.top500.org/list/2018/06/")
# parse the URL using Beauriful Soup
soup = BeautifulSoup(url.content, 'html.parser')
newtxt= ""
for record in soup.find_all('tr'):
tbltxt = ""
for data in record.find_all('td'):
tbltxt = tbltxt + "," + data.text
newtxt= newtxt+ "\n" + tbltxt[1:]
print(newtxt)
from bs4 import BeautifulSoup
import requests
url = requests.get("https://www.top500.org/list/2018/06/")
soup = BeautifulSoup(url.content, 'html.parser')
table = soup.find_all('table', attrs={'class':'table table-condensed table-striped'})
for i in table:
tr = i.find_all('tr')
for x in tr:
print(x.text)
或使用Pandas解析表格的最佳方法
import pandas as pd
table = pd.read_html('https://www.top500.org/list/2018/06/', attrs={
'class': 'table table-condensed table-striped'}, header = 1)
print(table)
它多次打印大量數據,因為在獲取每個<td></td>
的文本之后要打印的newtext
變量只是累加了所有值。 最簡單的方法是將行print(newtxt)
移到兩個for
循環之外-也就是說,完全不縮進。 然后,您應該看到所有文本的列表,其中每一行的內容都位於換行符之間,並且每一行中的每個單獨單元格都由逗號分隔。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.