python - 如何针对 bs4 抓取的特定维基百科表格元素?

标签 python python-3.x web-scraping beautifulsoup

here is what I'm trying to target with BeautifulSoup

这是迄今为止我的代码:

from bs4 import BeautifulSoup
soup = BeautifulSoup(website_url,'lxml')
my_table = soup.find('table',{'class':'wikitable sortable'})

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'https://en.wikipedia.org/wiki/2019%E2%80%9320_Wuhan_coronavirus_outbreak'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")
page_soup.tbody.tr?

我正在尝试定位此表格元素,但它不是唯一的。如何捕获这个名为“< td style...< b”的嵌套元素?

我可以做 page_soup.h1 来获取所有 h1 标签内容,但这里有很多重复标签,我需要一些帮助。我做了 UTFSE 但仍然很困惑。感谢您抽出时间。

最佳答案

如果我正确理解你的问题,你可以尝试这样的事情:

url = 'https://en.wikipedia.org/wiki/2019%E2%80%9320_Wuhan_coronavirus_outbreak'
import requests
from bs4 import BeautifulSoup as bs
resp = requests.get(url)


soup = bs(resp.text,'lxml')

tabs = soup.find('table',{'class':'wikitable sortable'})
tot = tabs.find_all('tr',{'style':'vertical-align:top'})
for t in tot:    
    rows = t.find_all('td',style=None)
    for r in rows:
        if r.text.strip() == "Total":
            print(m.nextSibling.text)

其背后的想法是目标数字2903位于带有(剥离)的行之后 文本总计Total 一词位于没有 style 属性的 td 标记中。我们找到该标签,目标号码位于其直接兄弟的文本中。

输出:

2,903

关于python - 如何针对 bs4 抓取的特定维基百科表格元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59938187/

相关文章:

python - argparse 选项的选项

html - Vba getElementById 导致运行时错误 '424'

Python urlopen 连接中止 - urlopen 错误 [Errno 10053]

Python fork 进程不会死

python - 如何使用 python PIL 获得平滑的文本?

python - 从具有 3 个 channel 的 numpy 数组绘制彩色图像

python - 将选择分组依据的结果复制到表中

python-3.x - 没有名为 'pandas' 的模块 - Jupyter、Python3 内核、TensorFlow 通过 Docker

python - Python 3.0 的哪些特性会改变你的日常编码?

python - 获取具有随机类名的元素