![](/img/trans.png)
[英]Python BeautifulSoup find all tags under a certain type of tag
[英]Find all tags of certain class only after tag with certain text
我在HTML中有一個很長的長表,因此標簽不會彼此嵌套。 它看起來像這樣:
<tr>
<td>A</td>
</tr>
<tr>
<td class="x">...</td>
<td class="x">...</td>
<td class="x">...</td>
<td class="x">...</td>
</tr>
<tr>
<td class ="y">...</td>
<td class ="y">...</td>
<td class ="y">...</td>
<td class ="y">...</td>
</tr>
<tr>
<td>B</td>
</tr>
<tr>
<td class="x">...</td>
<td class="x">...</td>
<td class="x">...</td>
<td class="x">...</td>
</tr>
<tr>
<td class ="y">I want this</td>
<td class ="y">and this</td>
<td class ="y">and this</td>
<td class ="y">and this</td>
</tr>
所以首先我要搜索樹以找到“B”。 然后我想在B之后使用類y獲取每個td標記的文本,但是在下一行表以“C”開始之前。
我試過這個:
results = soup.find_all('td')
for result in results:
if result.string == "B":
print(result.string)
這讓我得到了我想要的字符串B. 但是現在我想在此之后找到所有這些並且我沒有得到我想要的東西。
for results in soup.find_all('td'):
if results.string == 'B':
a = results.find_next('td',class_='y')
這給了我'B'之后的下一個td,這就是我想要的,但我似乎只能獲得第一個td標簽。 我想抓住所有具有類y的標簽,在'B'之后但在'C'之前(C沒有在html中顯示,但是遵循相同的模式),我想把它放到列表中。
我的結果列表是:
[['I want this'],['and this'],['and this'],['and this']]
基本上,您需要找到包含B
文本的元素。 這是你的出發點。
然后,使用find_next_siblings()
檢查此元素的每個tr
兄弟:
start = soup.find("td", text="B").parent
for tr in start.find_next_siblings("tr"):
# exit if reached C
if tr.find("td", text="C"):
break
# get all tds with a desired class
tds = tr.find_all("td", class_="y")
for td in tds:
print(td.get_text())
測試您的示例數據,它打印:
I want this
and this
and this
and this
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.