这是迄今为止我的代码:
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/