简单地说,我会这样做。
import pandas as pd
df = pd.read_html("https://ballotpedia.org/Alabama_Supreme_Court")[2]["Judge"]
print(df.to_list())
输出:
['Brad Mendheim', 'Kelli Wise', 'Michael Bolin', 'William Sellers', 'Sarah Stewart', 'Greg Shaw', 'Tommy Bryan', 'Jay Mitchell', 'Tom
Parker']
现在回到原来issue
的解决它,因为我个人喜欢解决真正的问题,而不是导航到替代解决方案。
有区别find
which 将只返回第一个element
但find_all
将返回 a list
of elements
。检查文档。
直接导入from bs4 import BeautifulSoup
而不是import bs4
因为它是 Python的 DRY 原则。
留下bs4
来处理内容,因为它是后台的任务之一。所以而不是r.text
使用r.content
现在,我们将深入到HTML
选择它:
from bs4 import BeautifulSoup
import requests
r = requests.get("https://ballotpedia.org/Alabama_Supreme_Court")
soup = BeautifulSoup(r.content, 'html.parser')
print([item.text for item in soup.select(
"table.wikitable.sortable.jquery-tablesorter a")])
现在,您必须阅读有关CSS-Selection 的内容
输出:
['Brad Mendheim', 'Kelli Wise', 'Michael Bolin', 'William Sellers', 'Sarah Stewart', 'Greg Shaw', 'Tommy Bryan', 'Jay Mitchell', 'Tom Parker']