python - 使用 python 缩小我从网站上抓取的内容

标签 python beautifulsoup find screen-scraping page-inspector

我正在尝试为网站练习我的 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将返回 listelements .检查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/

相关文章:

python - 枕头属性错误

python - 为什么将元组分配给带注释的变量需要括号?

python - 如何使用beautiful soup获取html中span标签的值?

python - 无法将 HTML 从网站正确转换为文本

python - 在 Python "requests"模块中,如何检查服务器是否已关闭或 500?

python - 在 Django 中从 View 导入模型

python - 使用 Beautiful Soup 解析 HTML 中的数据绑定(bind)标签

linux - 在线根据txt文件中的文件名查找并移动文件

c++ - 在C++中查找所有目录中的所有文件

multithreading - GNU 并行 : assign one thread for each node (directories and sub* directories) of an entire tree from a start directory