【发布时间】:2021-05-27 09:19:56
【问题描述】:
当我运行这段代码时,我可以看到标题列表填充了我想要的结果,但是它们被一些我不想保留的 html 包围。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
# barchart.com uses javascript, so for now I need selenium to get full html
url = 'https://www.barchart.com/stocks/quotes/qqq/constituents'
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
browser = webdriver.Chrome(options=chrome_options)
browser.get(url)
page = browser.page_source
# BeautifulSoup find table
soup = BeautifulSoup(page, 'lxml')
table = soup.find("table")
browser.quit()
# create list headers, then populate with th tagged cells
headers = []
for i in table.find_all('th'):
title = i()
headers.append(title)
所以我尝试了:
for i in table.find_all('th'):
title = i.text()
headers.append(title)
返回"TypeError: 'str' object is not callable"
这似乎在一些示例文档中有效,但那里使用的维基百科表格似乎比 Barchart 上的更简单。有什么想法吗?
【问题讨论】:
-
去掉括号
()。代替i.text(),使用i.text。 -
问得好,@朱利安!写得很好,格式很好,你向我们展示了你尝试了什么以及失败的地方。欢迎加入 StackOverflow 大家庭!
标签: python selenium web-scraping beautifulsoup html-table