我正在尝试为网站练习我的 python 抓取,但无法将其缩小到合理的大小,而 python 无法识别我的要求。例如,这是我的代码:
import bs4
import requests
url = requests.get('https://ballotpedia.org/Alabama_Supreme_Court')
soup = bs4.BeautifulSoup(url.text, 'html.parser')
y = soup.find('table')
print(y)
我正试图抓取阿拉巴马州最高法院法官的名字,但通过这段代码,我获得了太多信息。我已经尝试过诸如(第 6 行)
y = soup.find('table',{'class':'wikitable sortable'})`
但是我收到一条消息说搜索没有找到结果。
这是检查网页的图片。我的目标是让 thead 在我的代码中工作,但失败了!
我如何向 python 指定我只需要法官的名字?
非常感谢!
最佳答案
简单的说,我就这样吧。
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']
Now Moving back to the original
issue
to solve it as I personally love to fix the real issue without navigating to alternative solutions.
find
之间有区别这将只返回第一个 element
但是find_all
将返回 list
的 elements
.检查Documentation .
直接导入from bs4 import BeautifulSoup
而不是 import bs4
因为它是 The DRY Principle Python 的。
离开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']
关于python - 使用 python 缩小我从网站上抓取的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60839562/