背景:我正试着从这个支持足球的参考页面。中抓取一些表格--我是个完全的新手--所以很多技术术语最终都让我不知所措,但在试图理解如何解决这个问题的过程中,我无法理解。
具体问题:因为页面上有多个表,所以我想不出如何让python针对我想要的表。我在试着弄到防御工事的桌子。下面的代码是我到目前为止得到的,它是使用来自同一个站点的页面的从本教程中 --但是只有一个表。
样本代码:
#url we are scraping
url = "https://www.pro-football-reference.com/teams/nwe/2017.htm"
#html from the given url
html=urlopen(url)
# make soup object of html
soup = BeautifulSoup(html)
# we see that soup is a beautifulsoup object
type(soup)
#
column_headers = [th.getText() for th in
soup.findAll('table', {"id": "defense").findAll('th')]
column_headers #our column headers尝试:我意识到教程的方法对我不起作用,所以我尝试将soup.findAll部分更改为针对特定的表。但我反复听到一个错误:
AttributeError: ResultSet对象没有属性'findAll‘。你很可能把一张物品清单当成了一件物品。当您打算调用find()时,是否调用了find_all()?
当将其更改为“查找”时,错误将变为:
AttributeError:“NoneType”对象没有属性“查找”
老实说,我不知道我在做什么,也不知道这些是什么意思。我希望你能帮助我弄清楚如何定位这些数据,然后再把它刮掉。
谢谢,
发布于 2018-01-12 01:17:04
你在“防御”一词后面缺少一个"}“。试着在下面看看它是否有效。
column_headers = th.getText()用于soup.findAll('table',{"id":“国防”}).findAll(‘th’)
发布于 2018-01-12 01:17:55
首先,您需要使用soup.find('table', {"id": "defense"}).findAll('th') -找到一个表,然后找到它的所有'th‘标记。
另一个问题是,在该页面的html中注释掉了带有id "defense“的表:
<div class="placeholder"></div>
<!--
<div class="table_outer_container">
<div class="overthrow table_container" id="div_defense">
<table class="sortable stats_table" id="defense" data-cols-to-freeze=2><caption>Defense & Fumbles Table</caption>
<colgroup><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col><col></colgroup>
<thead>等等,我认为javascript没有隐藏它。BeautifulSoup不解析注释文本,因此您需要像在这个答案中一样在页面上找到所有注释的文本,查找其中包含id="defense"的注释文本,然后将该注释的文本输入BeautifulSoup。
如下所示:
from bs4 import Comment
comments = comments = soup.findAll(text=lambda text:isinstance(text, Comment))
defenseComment = next(c for c in comments if 'id="defense"' in c)
defenseSoup = BeautifulSoup(str(defenseComment))https://stackoverflow.com/questions/48217969
复制相似问题