python - 为什么我不能在使用 BeautifulSoup 抓取表格标题时使用“.text”来删除不需要的 HTML
问题描述
当我运行这段代码时,我可以看到标题列表填充了我想要的结果,但是它们被一些我不想保留的 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 上的更简单。有任何想法吗?
解决方案
正如@MendelG 指出的那样,错误在于i.text()
因为text
是属性而不是函数。
或者,您也可以使用get_text()
which 是一个函数。
我还建议添加 astrip()
以消除文本周围的多余空格。或者,如果您想使用get_text()
它,它内置:
title = i.get_text(strip=True)
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.text.strip()
# Or alternatively:
#title = i.get_text(strip=True)
headers.append(title)
print(headers)
这打印:
['Symbol', 'Name', '% Holding', 'Shares', 'Links']
推荐阅读
- mysql - 以及从哪里使用 mysql join
- c++ - 如何在不重复访问时验证 C++ 对象的状态
- vb.net - YAML 文件中的嵌套列表 - 在 VB.net 中创建类时遇到问题(eve online SDE)
- markdown - 如何使用 Markdown 对同一文档的部分进行链接引用,其中标题是带有空格的句子?
- erlang - 掌握 Erlang 消息
- webrtc - 使用WebRTC,是否每次不用TURN sever都能连接成功?
- javascript - 支持小写并包含搜索值的管道
- limit - 封装的 poscript 最大行数限制
- wildfly - FacesContext 在带有 JSF 2.3 的 Wildfly 14 中不可注入(Mojarra,主模块)
- safari - 按“离开页面”后如何在不刷新的情况下重置 Safari 12 beforeunload 事件?