2015-10-02 35 views
4

我在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之后但是在下一行表格以“C”开始之前抓取每个td标签的文本。

我已经试过这样:

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']] 

回答

3

基本上,你需要找到包含B文本的元素。这是你的出发点。

然后,检查每tr兄弟使用find_next_siblings()这个元素:

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 
+1

谢谢您的答复。这个对我有用。但是,我很幸运,因为我需要的是每次兄弟姐妹的最后一次。因为我不知道'C'会变成什么样子,宁愿他变得活跃起来,我怎么能让这个变得更好,所以它不管用。因此,如果文本是'C',而不是突破循环的迭代,我怎么能检查它不等于'B'。 – strahanstoothgap

相关问题