1
我試圖創建一個包含網頁上的「操作」表中的數據像這樣的一個分隔文本文件的文本分隔的文件:http://stats.swehockey.se/Game/Events/300978創建從HTML表格使用BeautifulSoup
我想每一行包括遊戲#(從URL的末尾開始),然後包括表格中的行。例如:
300972 | 60:00 | GK Out | OHK | 33. Hudacek, Julius
我還沒有能夠讓每一行實際分開。我試着通過每行和每列解析,使用一個剝離字符串列表,並通過不同的標籤,類和樣式進行搜索。
這是我目前有:
from bs4 import BeautifulSoup
import urllib.request
def createtext():
gamestr = urlstr + "|"
#Find all table lines. Create one pipe-delimited line for each.
aptext = gamestr
for el in soup.find_all('tr'):
playrow = el.find_all('td', 'tdOdd')
for td in playrow:
if(td.find(text=True)) not in ("", None, "\n"):
aptext = aptext + ''.join(td.text) + "|"
aptext = aptext + "\n" + gamestr
#Creates file with Game # as filename and writes the data to the file
currentfile = urlstr + ".txt"
with open(currentfile, "w") as f:
f.write(str(aptext))
#Grabs the HTML file and creates the soup
urlno = 300978
urlstr = str(urlno)
url = ("http://stats.swehockey.se/Game/Events/" + urlstr)
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
pbpdoc = response.read().decode('utf-8')
soup = BeautifulSoup(pbpdoc)
createtext()
感謝任何幫助或指導!
感謝您的回覆和代碼!當我嘗試使用它時,我遇到了這個錯誤:'NoneType'對象沒有屬性'find_parent' –
@NotDave好吧,看起來你有一箇舊的bs4版本 - 試着用'text'而不是'string'。 – alecxe
這個伎倆!非常感謝! –