2016-10-26 8 views
0

После поиска документа BeautifulSoup для строки, как мне получить таблицу, содержащую эту строку? У меня есть решение, которое работает на одном столе, что я знаком с:python 2.7 BeautifulSoup найти таблицу, содержащую определенную строку

Мой код выглядит следующим образом:

import mechanize 
from bs4 import BeautifulSoup 

sitemap_url = "https://www.rbi.org.in/scripts/sitemap.aspx" 

br = mechanize.Browser() 
br.addheaders = [('User-agent', 
'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1'), 
('accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')] 

response = br.open(sitemap_url) 
text = response.read() 
br.close() 

soup = BeautifulSoup(text, 'lxml') 

# Find the table containing the financial intermediaries. 

# First I find "Financial Intermediaries" in soup. 
fin_str = soup.find(text="Financial Intermediaries") 

# Next I step out through the parents 
# until it turns out that I have found the table. 
fin_tbl = fin_str.parent.parent.parent.parent 

Проблема в том, что я должен проверить результаты каждый раз, когда я шаг из документ. Как я могу добавить .parent, пока не увижу таблицу?

ответ

0

Append следующий код на программу:

# The first tag around the string is the parent. 
fn_in = fin_str.parent 

# Step out through the parents. 
def step_out(i): 
    if isinstance(i, element.NavigableString): 
     pass 
    return i.parent 

# Continue until 'table' is in the name of the tag. 
while not 'table' in fn_in.name: 
    fn_in = step_out(fn_in) 

 Смежные вопросы

  • Нет связанных вопросов^_^