如何获得按顺序
我正在使用BS4表中的文本作为如何获得按顺序
soup = BeautifulSoup(html_text)
table = soup.find("table", attrs={"class":"table_class"})
headings = [i.get_text() for i in table.find("tr").find_all("td")]
但我怎么能有序列2的findall所有元素的文字?我想下面
headings = [i.get_text() for i in table.find("tr").find_all("td").find_all("div")]
如果我只是用find("td")
我只得到一个价值无法从表中的所有值。 我遍历"td"
,并为每一个元素如何获得"div"
只要你有涉及iterables /迭代器有问题,看在itertools。
from itertools import chain
headings = [i.get_text() for i in chain.from_iterable(x.find_all("div") for x in table.find("tr").find_all("td"))]
还有一个更简单,更简洁的方式 - 一个CSS selector:
[elm.get_text() for elm in soup.select("table.table_class tr td div")]
我可以遍历多个迭代? ''tr“'在''thead''下,所以我可以做些像'soup.select(”table.table_class thead trdd div“)]''。我试过了,但它只打印了一行 – user2661518
@ user2661518'table.table_class tr td div' - 这将遍历表中的每个'tr',包括'thead'中的'tr'行。 'table.table_class thead tr td div'让你一行,因为表头中有一行.. – alecxe
@alexce是我有3行每个都以'“thead”开头,但上面只给了我一行。我可以得到所有3行吗?对不起,我是新来的CSS – user2661518
@ user2661518这真的很难测试没有实际的测试数据。我假设有这张表,第一个'tr'有几个'td',每个都包含'div's,对吧? – L3viathan
我的工作很糟糕 – user2661518
它可以很好地工作,但是你可以迭代多个迭代? ''tr“'在''thead''下,所以我可以在'find_all(”thead“)下面做'find_all(”tr“)'' – user2661518