【发布时间】:2017-01-10 05:55:38
【问题描述】:
.select() 元素允许我根据 CSS 选择器从网页中获取一个元素,但这将搜索整个网页。我将如何使用 .select() 但只搜索特定元素的子元素。例如:
<!-- Simplified example of the structure -->
<ul>
<li>
<div class="foo">foo content</div>
<div class="bar">bar content</div>
<div class="baz">baz content</div>
</li>
<li>
<!-- We can't assume that foo, bar, and baz will always be there -->
<div class="foo">foo content</div>
<div class="baz">baz content</div>
</li>
<li>
<div class="foo">foo content</div>
<div class="bar">bar content</div>
<div class="baz">baz content</div>
</li>
</ul>
我想用一种方式说:
对于<li>[0] foo 包含值"foo content",bar 包含值"bar content" 等等。
目前我的解决方案如下:
foos = soup.select("div.foo")
bars = soup.select("div.bar")
bazs = soup.select("div.baz")
for i in range(len(foos)):
print("{i} contains: {} and {} and {}".format(i=i, foos[i], bars[i], bazs[i]))
这在大多数情况下都有效。但是,当其中一个 li 缺少一个元素时,它就会完全崩溃。就像我在 HTML 中展示的那样,我们不能假设会出现三个 bar、baz 和 foo 元素。
因此,我将如何仅搜索 lis 的子项。因此我可以这样做:
for i in soup.select("li"):
#how would i do this:
foo = child_of("li", "div.foo")????
bar = child_of("li", "div.bar")????
baz = child_of("li", "div.baz")????
【问题讨论】:
标签: python css python-3.x beautifulsoup bs4