首页 > 解决方案 > 为什么我不能在使用 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 上的更简单。有任何想法吗?

标签: pythonseleniumweb-scrapingbeautifulsouphtml-table

解决方案


正如@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']

推荐阅读