python - 如何从 URL 列表中获取属性 ('innerHTML' ) - Selenium?

标签 python loops selenium

我在 Python 中使用 Selenium 进行网页抓取。我正在使用 xpath 提取网站的部分内容。

我想知道如何使用循环提取 URL 列表并将它们保存到字典中。

mylist_URLs = ['https://www.sec.gov/cgi-bin/own-disp? action=getowner&CIK=0001560258',
'https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=0000034088',
'https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=0001048911']

我的下面的编码仅适用于 1 个网址...

driver = webdriver.Chrome(r'xxx\chromedriver.exe')
driver.get('https://www.sec.gov/cgi-bin/own-disp?action=getowner&CIK=0000104169')

driver.find_elements_by_xpath('/html/body/div/table[1]/tbody/tr[2]/td/table/tbody/tr[1]/td')[0].get_attribute('innerHTML')

感谢您的帮助。

最佳答案

您可以使用简单的 for every 循环与 WebDriverWait 来确保在获取innerHTML 之前加载表格。

添加以下导入:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

脚本:

mylist_URLs = ['https://www.sec.gov/cgi-bin/own-disp? action=getowner&CIK=0001560258',
'https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=0000034088',
'https://www.sec.gov/cgi-bin/own-disp?action=getissuer&CIK=0001048911']
# open the browser
driver = webdriver.Chrome(r'xxx\chromedriver.exe')
# iterate through all the urls
for url in mylist_URLs:
    print(url)
    driver.get(url)
    # wait for the table to present
    element = WebDriverWait(driver,30).until(EC.presence_of_element_located((By.XPATH, "(//table[1]/tbody/tr[2]/td/table/tbody/tr[1]/td)[1]"))
    # now get the element innerHTML
    print(element.get_attribute('innerHTML')))

关于python - 如何从 URL 列表中获取属性 ('innerHTML' ) - Selenium?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57066938/

相关文章:

python - 将 Excel 读取到数据帧时出现解析器错误 Pandas

java - 对多个数组元素执行 JUnit 断言 - 当一个元素失败时如何处理?

javascript - 如何在从 Angular JavaScript 提供数据的页面上执行 Scrapy 和 Selenium?

javascript - 在 Javascript 中一次通过一组 4 个元素循环遍历数组?

java - 没有 Thread.sleep Webdriver IE 将给出 “unable to find element” 异常

python - 为什么在 Sublime Text 下写入 STD_OUTPUT_HANDLE 会崩溃?

python - GAE : Convert model to subclass of polymodel

python - 理解 Python 中的阶乘

C 编程 : Help Understanding for loop

ruby-on-rails - Rails 中 "each .. do"或 "for .. in"循环之间的差异