2013-11-22 3 views
2

Я пытаюсь очистить и записать вывод в той же строке для каждой итерации, используя следующий код.AttributeError: объект 'tuple' не имеет атрибута '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)]*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] 

сейчас я получаю выход как

A K Ponnusamy & Co 
[email protected] 
Manufacturing of Rough Castings 
Aelenke PL Industrials 

All types of Pulleys 
Agri Pump Industries 

Submersible Pumpsset Jet Pumps Centrifugal Monoblocks Motor & pumps 
Akshaya Engineering 

pumpsets 
Altech Industries 
[email protected]|www.altechindustries.org 
Engineering College Lab Equipment (FM and Therai lab Equipment) 
Ammurun Foundry 
[email protected]|www.ammarun.com 
Grey Iron & S.G. Iron Rough Castings 
Anugraha Valve Castings Ltd 
[email protected] 
valve & spares 
Apex Bright Bars (Cbe) Pvt Ltd 
[email protected] 

Я хотел, чтобы это было как

A K Ponnusamy & Co |[email protected] | Manufacturing of Rough Castings 
Aelenke PL Industrials | | All types of Pulleys 
+0

Что 'почтовый (* [ИТЭР (TdS)] * 2)' должен делать? –

+1

'[','. Join (data) для x в данных]' Не делает то, что вы ожидаете от него: '[", ". Join (x) для x в ['a', 'b', ' c ',' d ']] == [' a ',' b ',' c ',' d '] '. Чтобы объединить элементы вместе в одну строку, разделенную запятыми, выполните команды '", ". Join (['a', 'b', 'c', 'd']) ==" a, b, c, d " ' – jonrsharpe

+0

Previsouly Я использовал' ', '. Join (data)' only. Он все еще писал в отдельной строке. –

ответ

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) 

Что дает следующую ouyput:

Name & Address of the Company | E Mail & Web | Product Manufactured 
A K Ponnusamy & Co | [email protected] | Manufacturing of Rough Castings 
Aelenke PL Industrials | | All types of Pulleys 
... 
+0

Спасибо. Это работает. –

4

ваш 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) 

Возвращает:

Name & Address of the Company, E Mail & Web, Product Manufactured 
A K Ponnusamy & Co, [email protected], Manufacturing of Rough Castings 
Aelenke PL Industrials, All types of Pulleys 
Agri Pump Industries, Submersible Pumpsset, Jet Pumps, Centrifugal Monoblocks, Motor & pumps 
... more skipped ... 

Первые TD метки на этой странице, включают заголовки, однако, вы можете пропустить их.

+0

Он возвращается в одной строке, чего я не хочу. Если требуется, чтобы каждый набор данных с каждой итерации находился в строке. не весь выход. Надеюсь, я понятен. –

+0

Это ** не ** возвращение двух идентичных тд-тегов. Он объединяет теги td, по два за раз. –

+0

Вы правы, спасибо, что указали, что это имеет больше смысла. –

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