AttributeError:“tuple”对象没有“find\u all”属性

2024-04-25 20:03:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用以下代码为每次迭代在同一行中获取和写入输出。在

import urllib2
from bs4 import BeautifulSoup
import re
page = urllib2.urlopen("http://www.siema.org/members.html")
soup = BeautifulSoup(page)
tds = soup.findAll('td', attrs={'class':'content'})
for table in zip(*[iter(tds)]*2):
    data = [re.sub('\s+', ' ', text).strip().encode('utf8') for text in table.find_all(text=True) if text.strip()]
    print [','.join(data) for x in data]

现在我得到的输出是

^{pr2}$

我希望它像

A K Ponnusamy & Co  |cjm@yahoo.co.in  |  Manufacturing of Rough Castings
Aelenke PL Industrials |    | All types of Pulleys

Tags: of代码textinimportrefordata
2条回答

这与前面的答案非常相似,但输出稍微更理想。在

for table in zip( *[iter(tds)]*3 ):
    row = [', '.join([re.sub('\s+', ' ', text).strip().encode('utf8') 
                        for text in td.find_all(text=True) 
                        if text.strip()])
                       for td in table]
    print ' | '.join(row)

得到以下输出:

^{pr2}$

您的zip(*[iter(tds)]*2正在返回包含td标记的元组列表。因此,表变量是一个元组,它没有find_all方法。在

这个:

import urllib2
from bs4 import BeautifulSoup
import re
page = urllib2.urlopen("http://www.siema.org/members.html")
soup = BeautifulSoup(page)
tds = soup.findAll('td', attrs={'class':'content'})
for table in zip( *[iter(tds)]*3 ):
    data = []
    for td in table:
        data += [re.sub('\s+', ' ', text).strip().encode('utf8') for text in td.find_all(text=True) if text.strip()]
    print ', '.join(data)

退货:

^{pr2}$

该页面上的第一个TD标记包括标题,但是您可能希望跳过这些。在

相关问题 更多 >

    热门问题