python - 数据下载延迟从网页中抓取数据
问题描述
我已尝试在此站点上查看有关此问题的几个问题,但我无法使他们的解决方案起作用。我正在使用带有 chrome 无头浏览器的 python 和 selenium 从 vanguard 抓取债券数据。Vanguard 延迟加载页面上的数据,我无法弄清楚如何正确获取数据。
我正在尝试从此网页加载数据,特别是基金事实表中的数据
当我像往常一样尝试这样做时,我得到了
<iframe data-delayed-src="https://fls.doubleclick.net/activityi;src=844392;u7=vgmf;type=remar743;cat=mutua911;u1=prd;ord=1632433243910?" id="floodIframe" src="https://fls.doubleclick.net/activityi;src=844392;u7=vgmf;type=remar743;cat=mutua911;u1=prd;ord=1632433243910?"></iframe>
所以我尝试使用这行代码让浏览器等待数据加载。
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "data-ng-class")))
我确信这是在正确的轨道上,但我不知道如何正确判断我应该等待识别哪些元素以及我是否正确执行。有没有办法让我等到 iframe data-delayed-src 元素消失才能获取数据?
我已经看到它与 By.ID 的用法,但我没有在数据 html 中看到任何我想要的具有 id 的元素。
这是我正在使用的代码
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
import os
dirname = os.path.dirname(__file__)
options = webdriver.ChromeOptions()
options.add_argument('--headless')
browser = webdriver.Chrome(options=options, executable_path=os.path.join(dirname, 'chromedriver'))
symbol = 'vbirx'
url_vanguard = 'https://investor.vanguard.com/mutual-funds/profile/overview/{}'
browser.get(url_vanguard.format(symbol))
# WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "data-ng-class")))
html = browser.page_source
mySoup = BeautifulSoup(html, 'html.parser')
htmlData = mySoup.find('table',{'role':'presentation'})
table = htmlData.find('tbody')
print('table: \n',table)
表格打印出缺少我想要的所有数据
<tbody>
<!-- ngRepeat: item in genericTableData.items -->
</tbody>
解决方案
我在 WebDriverWait 语句中使用了 Fund 事实表的 XPath 来使其工作。
代码片段:-
symbol = 'vbirx'
url_vanguard = 'https://investor.vanguard.com/mutual-funds/profile/overview/{}'
browser.get(url_vanguard.format(symbol))
#waiting for the fund facts table to load
WebDriverWait(browser, 15).until(EC.presence_of_element_located((By.XPATH,'//*[@class="summary-table historical-table col2Wide"]')))
html = browser.page_source
mySoup = BeautifulSoup(html, 'html.parser')
htmlData = mySoup.find('table',{'role':'presentation'})
table = htmlData.find('tbody')
rows = table.find_all('td')
for row in rows:
span=row.find('span')
print(span.text)
推荐阅读
- c - 在不使用函数 isdigit 的情况下使用 fgets 时如何检查用户输入是否为字符串?
- excel - Excel V查找多个值问题
- c - 如何在 C 中打印多字符常量?
- sql - 使用输入“'abc','xyz'”调用 SQL 存储过程
- android - 如何在屏幕旋转期间保存 MutableList 的状态
- javascript - MongoDB在双重嵌套数组中获取最大日期
- angular - ngx-daterangepicker-material 以上个月和当前月份而不是当前和下个月打开
- google-bigquery - 阻止用户删除 BigQuery 表
- ruby - 每次出现该事件时,在 logstash 中使用 Ruby 过滤器对字段的值求和
- python - 如何按 Python 中的第一个元素重新分类元组列表?