我正在尝试从网站的 table="table-main"中提取所有 TD 值:http://www.oddsportal.com/basketball/usa/nba/results/
我正在使用 Scrapy 和 Python 2.7
从 Scrapy Shell 我可以通过以下方式获取表格:
response.xpath('//*[@id="tournamentTable"]')
但我似乎无法获得该表的任何 TR 或 TD。
response.xpath('//*[@id="tournamentTable"]/tbody')
and response.xpath('//*[@id="tournamentTable"]/tbody/tr')
返回一个空列表。我怀疑该表可能是动态创建的。任何人都可以帮助我从该表中删除所有球队名称、分数和赔率。我已经坚持了一段时间。
这个问题与人们推荐的不同,在这里重复:Scrapy not finding table因为那个问题是关于拿到 table 的。这道题是关于获取表中数据的。
最佳答案
是的,结果是通过对网站 API 的额外调用加载的。在这种情况下,向 http://fb.oddsportal.com/ajax-sport-country-tournament-archive/3/MmbLsWh8/X0/1/-1/1/?_=1446338252826 发出请求.
我不确定您是否可以在蜘蛛程序中对 URL 进行硬编码,因为至少 URL 的这些 3
和 MmbLsWh8
部分实际上来自主页上的 script
标签:
<script type="text/javascript">
//<![CDATA[
var op = new OpHandler();if(!page)var page = new PageTournament({"id":"MmbLsWh8","sid":3,"cid":200,"archive":true});var menu_open = null;vJs();op.init();if(page && page.display)page.display(); var sigEndPage = true;
try
{
if (sigEndJs)
{
globals.onPageReady();
}
} catch (e)
{
}
//]]>
</script>
此外,还有一个 _
参数,看起来像一个时间戳。
调用此 AJAX url 将返回一个 JSONP 响应,其中包含 NBA 结果的 HTML 代码。您需要从响应中提取 HTML 代码(例如使用正则表达式),将其提供给 Selector
并提取结果。一些来自 shell 的示例代码可以帮助您入门:
$ scrapy shell http://www.oddsportal.com/basketball/usa/nba/results/
In [1]: fetch("http://fb.oddsportal.com/ajax-sport-country-tournament-archive/3/MmbLsWh8/X0/1/-1/1/?_=1446338252826")
In [2]: import re
In [3]: pattern = re.compile(r'"html":"(.*?)"}', re.MULTILINE | re.DOTALL)
In [4]: import scrapy
In [5]: selector = scrapy.Selector(text=pattern.search(response.body).group(1))
In [6]: # TODO: now use the selector to extract the desired data
关于python - Scrapy 从动态表中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33458025/