【发布时间】:2017-06-14 06:40:09
【问题描述】:
我正在尝试使用 BeautifulSoup 和 Python 中的请求来提取播放数据,但是此代码只是为数组“table”返回一个空数组 []。我对这些库比较陌生,但是在使用类似网站(即来自其他大学游戏的其他播放数据)执行类似任务时,我使用了类似的语法。我有兴趣提取的文本包含在以“第 1 局顶部”、“第 2 局底部”等开头的表格中。如果有任何不清楚的地方,请发表评论以澄清。谢谢!
from bs4 import BeautifulSoup
import requests
header = {'User-agent' : 'Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5'}
url = requests.get("http://www.belmontbruins.com/sports/m-basebl/2016-17/boxscores/20170407_c6td.xml?view=plays", headers = header).text
soup = BeautifulSoup(url, 'html.parser')
with open('test.txt','w+') as myfile:
table = soup.find_all('table', text = ['Top', 'Bottom'])
print(table)
for eachtable in table:
rows = eachtable.find_all('tr')
for tr in rows:
cols = tr.find_all('td')
for td in cols:
myfile.write(td.text + '\n')
【问题讨论】:
-
我不清楚您要做什么?如果以 'Top of 1st Inning'、“Bottom of 2nd Inning' 开头,您是否要提取所有
文本。我没听错吗?只有一张桌子吗? 因此,如果您检查给定网站的 HTML,则会有单独的表格包含该半局的逐场比赛数据(或字符串)(即第一局的顶部,第一局的底部)第一等)。本质上,我希望能够将要提取的表格缩小到仅包含关键字“Top”和“Bottom”的表格,然后我将打印文本,例如“MCFARLAND,Daniel flyed out to lf to left center”。 '到一个文本文件。要回答您的问题,有多个表格,但是我想从每个表格中提取文本。 好吧,我正在更新代码... :-)
标签: python web-scraping beautifulsoup python-requests