0

这是一个特定于上下文的问题,关于如何使用 BeautifulSoup 来解析 python2.7 中的 html 表。

我想在这里提取 html 表并将其放在 tab-delim csv 中,并尝试使用 BeautifulSoup。

上下文代码:

proxies = {
    "http://": "198.204.231.235:3128",
}
site = "http://sloanconsortium.org/onlineprogram_listing?page=11&Institution=&field_op_delevery_mode_value_many_to_one[0]=100%25%20online"

r = requests.get(site, proxies=proxies)
print 'r: ', r
html_source = r.text
print 'src: ', html_source
soup = BeautifulSoup(html_source)

为什么这段代码没有得到第 4 行?

soup.find('table','views-table cols-6').tr[4]

我将如何打印出第一行(不是标题行)中的所有元素?

4

1 回答 1

2

好的,有人可能会给你一个单线,但以下应该让你开始

table = soup.find('table', class_='views-table cols-6')                                                                                                                                                                                                                        
for row in table.find_all('tr'):                                                                                                                                                                                                                                               
    row_text = list()                                                                                                                                                                                                                                                          
    for item in row.find_all('td'):                                                                                                                                                                                                                                            
        text = item.text.strip()                                                                                                                                                                                                                                               
        row_text.append(text.encode('utf8'))                                                                                                                                                                                                                                   
    print row_text

我相信您的 tr[4] 被认为是一个属性,而不是您想象的索引。

于 2013-07-23T19:24:36.897 回答