繁体   English   中英

从基于下拉菜单更改的数据表中抓取“ li”标签

[英]Scrape 'li' tags from a data table that changes based on drop-down menu

我正在尝试从此网站上的数据表中抓取数据:[ http://www.oddsshark.com/ncaab/lsu-alabama-odds-february-18-2017-744793]

该站点具有多个选项卡,这些选项卡更改了html(我正在“匹配”选项卡中工作)。 在该matchup选项卡中,有一个下拉菜单,用于更改我尝试访问的数据表。 我要访问的表中的项目是无序列表中的“ li”标签。 我只想从下拉菜单的“总体”类别中抓取数据。

我一直无法访问所需的数据。 我尝试访问的项目以“ noneType”的形式返回。 有没有办法做到这一点?

url = "http://www.oddsshark.com/ncaab/lsu-alabama-odds-february-18-2017-
744793"  
html_page = requests.get(url)
soup = BeautifulSoup(html_page.content, 'html.parser')

dataList = []
for ultag in soup.find_all('ul', {'class': 'base-list team-stats'}):
    print(ultag)
    for iltag in ultag.find_all('li'):
        dataList.append(iltag.get_text())

因此,问题在于,您尝试从中提取数据的选项卡的内容是使用React JS动态加载的。 因此,您必须使用Python中的selenium模块来打开浏览器,以编程方式单击列表元素“ Matchup”,然后在单击它后获取源。

在我的Mac上,我按照以下说明安装了selenium和chromewebdriver:

https://gist.github.com/guylaor/3eb9e7ff2ac91b7559625262b8a6dd5f

然后按照以下说明对python文件签名,以使OS X防火墙在尝试运行它时不会向我们抱怨: 将Python添加到OS X防火墙选项?

然后运行以下python3代码:

import os
import time
from selenium import webdriver
from bs4 import BeautifulSoup as soup

# Setup Selenium Chrome Web Driver
chromedriver = "/usr/local/bin/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)

# Navigate in Chrome to specified page.
driver.get("http://www.oddsshark.com/ncaab/lsu-alabama-odds-february-18-2017-744793")

# Find the matchup list element using a css selector and click it.
link = driver.find_element_by_css_selector("li[id='react-tabs-0'").click()

# Wait for content to load
time.sleep(1)

# Get the current page source.
source = driver.page_source

# Parse into soup() the source of the page after the link is clicked and use "html.parser" as the Parser.
soupify = soup(source, 'html.parser')

dataList = []
for ultag in soupify.find_all('ul', {'class': 'base-list team-stats'}):
    print(ultag)
    for iltag in ultag.find_all('li'):
        dataList.append(iltag.get_text())

# We are done with the driver so quit.
driver.quit()

希望这会有所帮助,因为我注意到这与我刚刚在这里解决的问题类似-Beautifulsoup没有达到子元素

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM