Python 刮取数据时的语法问题
我使用这些代码是为了从中获取所有boxscore URL。在我得到这些boxscore URL后,我想循环遍历它们,以获取每个团队的季度数据,但无论我如何格式化代码,我的语法似乎总是不正确Python 刮取数据时的语法问题,python,web-scraping,Python,Web Scraping,我使用这些代码是为了从中获取所有boxscore URL。在我得到这些boxscore URL后,我想循环遍历它们,以获取每个团队的季度数据,但无论我如何格式化代码,我的语法似乎总是不正确 如果可能的话,我想通过获取比赛信息、官员和每场比赛的预期分数来获取更多的得分数据。如果您稍微将循环修改为: import requests from bs4 import BeautifulSoup import csv from urlparse import urljoin import urllib2
如果可能的话,我想通过获取比赛信息、官员和每场比赛的预期分数来获取更多的得分数据。如果您稍微将循环修改为:
import requests
from bs4 import BeautifulSoup
import csv
from urlparse import urljoin
import urllib2
from lxml import html
base_url = 'http://www.pro-football-reference.com' # base url for concatenation
data = requests.get("http://www.pro-football-reference.com/years/2014/games.htm") #website for scraping
soup = BeautifulSoup(data.content)
list_of_cells = []
for link in soup.find_all('a'):
if link.has_attr('href'):
if link.get_text() == 'boxscore':
url = base_url + link['href']
for x in url:
response = requests.get('x')
html = response.content
soup = BeautifulSoup(html)
table = soup.find('table', attrs={'class': 'stats_table x_large_text'})
for row in table.findAll('tr'):
for cell in row.findAll('td'):
text = cell.text.replace(' ', '')
list_of_cells.append(text)
print list_of_cells
对于与“boxscore”文本链接的每个页面,返回评分表中每行的每个单元格
我发现现有代码存在以下问题:
您试图循环浏览为“boxscore”链接返回的href
中的每个字符
您总是请求字符串'x'
这不是什么问题,但我更改了表选择器,以通过其id
“评分”而不是类来标识表。ID在页面中至少应该是唯一的(尽管没有guarentee)
我建议您在主循环(例如score\u table=soup.find('table')…
)中查找包含所需数据的每个表(或HTML元素),但移动解析该数据的代码(例如)
…转换为一个单独的函数,该函数返回所述数据(您提取的每种数据类型一个),只是为了使代码更易于管理。代码缩进越多,以处理if
测试和for
循环,就越难遵循流程。例如:
for row in table.findAll('tr'):
for cell in row.findAll('td'):
text = cell.text.replace(' ', '')
list_of_cells.append(text)
print list_of_cells
for row in table.findAll('tr'):
for cell in row.findAll('td'):
text = cell.text.replace(' ', '')
list_of_cells.append(text)
print list_of_cells
score_table = soup.find('table', attrs={'id': 'scoring'})
score_data = parse_score_table(score_table)
other_table = soup.find('table', attrs={'id': 'other'})
other_data = parse_other_table(other_table)