1

такое дерево вот

Новичок в парсинге. Не смог найти ответ на свой вопрос в гугле.

Пытался до этого получить названия сериалов и картинки к ним с сайта лостфильм.тв - всё получилось. Решил продолжить изучение, зашел на свой любимый трекер rutor.org и ничего не получается у меня. Хочу вытащить названия торрентов, но названия хранятся в ссылках с тегом 'а', все находятся в теге tr с классом gai или tum, но! там несколько тегов ссылочных 'a'. Как правильно поступить - ума не приложу. Мой код мне ничего не дает. Подскажите что не так делаю.

С лостфильмом всё проканало, а здесь не хочет

import requests
from bs4 import BeautifulSoup

url = 'http://rutor.info/search/0/1/0/0/2018'

r = requests.get(url).text

soup = BeautifulSoup(r, 'html.parser')

trs = soup.findAll('tr', {'class':'gai'})


for link in trs:
    text = link.find('a')
    print (text.contents[0])
<a href="/torrent/667673/veb-kamera_cam-2018-webrip-kpk-l2" style="font-size: 12px !important; line-height: 14.6667px !important;">Веб-камера / Cam (2018) WEBRip | КПК  | L2 </a>

кусок html:

    <table style="font-size: 16px !important; line-height: 19.3333px      !important;" width="100%"><tbody style="font-size: 16px !important; line-height: 19.3333px !important;"><tr class="backgr" style="font-size: 16px !important; line-height: 19.3333px !important;"><td style="font-size: 12px !important; line-height: 14.6667px !important;" width="10px">Добавлен</td><td colspan="2" style="font-size: 12px !important; line-height: 14.6667px !important;">Название</td><td style="font-size: 12px !important; line-height: 14.6667px !important;" width="1px">Размер</td><td style="font-size: 12px !important; line-height: 14.6667px !important;" width="1px">Пиры</td></tr><tr class="gai" style="font-size: 16px !important; line-height: 19.3333px !important;"><td style="font-size: 12px !important; line-height: 14.6667px !important;">30&nbsp;Ноя&nbsp;18</td><td style="font-size: 12px !important; line-height: 14.6667px !important;"><a class="downgif" href="http://d.rutor.info/download/653854" style="font-size: 12px !important;"><img src="http://s.rutor.info/i/d.gif" alt="D"></a><a href="magnet:?xt=urn:btih:9e0b073af1107ba41936b3b487bd16bb31591d0b&amp;dn=rutor.info&amp;tr=udp://opentor.org:2710&amp;tr=udp://opentor.org:2710&amp;tr=http://retracker.local/announce" style="font-size: 12px !important;"><img src="http://s.rutor.info/i/m.png" alt="M"></a>
<a href="/torrent/653854/kak-zhenit-holostjaka_destination-wedding-2018-bdrip-ot-megapeer-itunes" style="font-size: 12px !important; line-height: 14.6667px !important;">Как женить холостяка / Destination Wedding (2018) BDRip от MegaPeer | iTunes </a></td> <td style="font-size: 12px !important; line-height: 14.6667px !important;" align="right">39<img src="http://s.rutor.info/i/com.gif" alt="C"></td>
<td style="font-size: 12px !important; line-height: 14.6667px !important;" align="right">1.43&nbsp;GB</td><td style="font-size: 12px !important; line-height: 14.6667px !important;" align="center"><span class="green" style="font-size: 12px !important; line-height: 14.6667px !important;"><img src="http://s.rutor.info/t/arrowup.gif" alt="S">&nbsp;27</span>&nbsp;<img src="http://s.rutor.info/t/arrowdown.gif" alt="L"><span class="red" style="font-size: 12px !important; line-height: 14.6667px !important;">&nbsp;32</span></td></tr><tr class="tum" style="font-size: 16px !important; line-height: 19.3333px !important;"><td style="font-size: 12px !important; line-height: 14.6667px !important;">30&nbsp;Ноя&nbsp;18</td><td style="font-size: 12px !important; line-height: 14.6667px !important;"><a class="downgif" href="http://d.rutor.info/download/667726" style="font-size: 12px !important;"><img src="http://s.rutor.info/i/d.gif" alt="D"></a><a href="magnet:?xt=urn:btih:9ad5d732c361692a1c0923f1abca206cd5c3a359&amp;dn=rutor.info&amp;tr=udp://opentor.org:2710&amp;tr=udp://opentor.org:2710&amp;tr=http://retracker.local/announce" style="font-size: 12px !important;"><img src="http://s.rutor.info/i/m.png" alt="M"></a>
<a href="/torrent/667726/kak-zhenit-holostjaka_destination-wedding-2018-bdremux-1080p-ot-selezen-itunes" style="font-size: 12px !important; line-height: 14.6667px !important;">Как женить холостяка / Destination Wedding (2018) BDRemux 1080p от селезень | iTunes </a>
12
  • Добавьте, пожалуйста, в вопрос кусок html, из которого вы хотите вытащить названия (кнопка править)
    – gil9red
    30 ноя 2018 в 12:31
  • блин, не могу понять как добавить 30 ноя 2018 в 12:34
  • Попробуйте так: print(text.text) Кст, а можете добавить кусок той таблицы с ссылками?
    – gil9red
    30 ноя 2018 в 12:37
  • Можно попробовать искать нужные тебе части сроки посредством регулярных выражений, зачастую работает быстрее и надёжнее и мало зависит от изменений структуры самой страницы на которой ты ищешь. 30 ноя 2018 в 12:41
  • ничего не выдало. пусто. если запринтить trs, то выдаст пустой список. Имеете ввиду код html ? 30 ноя 2018 в 12:41

1 ответ 1

2

Попробуйте:

import requests
from bs4 import BeautifulSoup

url = 'http://rutor.info/search/0/1/0/0/2018'

rs = requests.get(url)
root = BeautifulSoup(rs.content, 'html.parser')

for tr in root.select('tr.gai'):
    tds = tr.select('td')
    
    # У второго td нужные нам <a>
    td = tds[1]
    
    # Выводим текст ячейки
    print(td.text)

Если нужно именно у ссылки вытащить текст, то:

...

for tr in root.select('tr.gai'):
    tds = tr.select('td')
    
    # У второго td берем третий <a>
    a = tds[1].select('a')[2]
    
    # Выводим текст ссылки
    print(a.text)

UPD.

Взял код из вопроса:

text = """
<table style="font-size: 16px !important; line-height: 19.3333px      !important;" width="100%">
<tbody style="font-size: 16px !important; line-height: 19.3333px !important;">
    <tr class="backgr" style="font-size: 16px !important; line-height: 19.3333px !important;">
        <td style="font-size: 12px !important; line-height: 14.6667px !important;" width="10px">Добавлен</td><td colspan="2" style="font-size: 12px !important; line-height: 14.6667px !important;">Название</td><td style="font-size: 12px !important; line-height: 14.6667px !important;" width="1px">Размер</td><td style="font-size: 12px !important; line-height: 14.6667px !important;" width="1px">Пиры</td>
    </tr>
    <tr class="gai" style="font-size: 16px !important; line-height: 19.3333px !important;"><td style="font-size: 12px !important; line-height: 14.6667px !important;">30&nbsp;Ноя&nbsp;18</td><td style="font-size: 12px !important; line-height: 14.6667px !important;"><a class="downgif" href="http://d.rutor.info/download/653854" style="font-size: 12px !important;"><img src="http://s.rutor.info/i/d.gif" alt="D"></a><a href="magnet:?xt=urn:btih:9e0b073af1107ba41936b3b487bd16bb31591d0b&amp;dn=rutor.info&amp;tr=udp://opentor.org:2710&amp;tr=udp://opentor.org:2710&amp;tr=http://retracker.local/announce" style="font-size: 12px !important;"><img src="http://s.rutor.info/i/m.png" alt="M"></a>
        <a href="/torrent/653854/kak-zhenit-holostjaka_destination-wedding-2018-bdrip-ot-megapeer-itunes" style="font-size: 12px !important; line-height: 14.6667px !important;">Как женить холостяка / Destination Wedding (2018) BDRip от MegaPeer | iTunes </a></td> <td style="font-size: 12px !important; line-height: 14.6667px !important;" align="right">39<img src="http://s.rutor.info/i/com.gif" alt="C"></td>
        <td style="font-size: 12px !important; line-height: 14.6667px !important;" align="right">1.43&nbsp;GB</td><td style="font-size: 12px !important; line-height: 14.6667px !important;" align="center"><span class="green" style="font-size: 12px !important; line-height: 14.6667px !important;"><img src="http://s.rutor.info/t/arrowup.gif" alt="S">&nbsp;27</span>&nbsp;<img src="http://s.rutor.info/t/arrowdown.gif" alt="L"><span class="red" style="font-size: 12px !important; line-height: 14.6667px !important;">&nbsp;32</span></td>
    </tr>
    <tr class="tum" style="font-size: 16px !important; line-height: 19.3333px !important;"><td style="font-size: 12px !important; line-height: 14.6667px !important;">30&nbsp;Ноя&nbsp;18</td><td style="font-size: 12px !important; line-height: 14.6667px !important;"><a class="downgif" href="http://d.rutor.info/download/667726" style="font-size: 12px !important;"><img src="http://s.rutor.info/i/d.gif" alt="D"></a><a href="magnet:?xt=urn:btih:9ad5d732c361692a1c0923f1abca206cd5c3a359&amp;dn=rutor.info&amp;tr=udp://opentor.org:2710&amp;tr=udp://opentor.org:2710&amp;tr=http://retracker.local/announce" style="font-size: 12px !important;"><img src="http://s.rutor.info/i/m.png" alt="M"></a>
    <a href="/torrent/667726/kak-zhenit-holostjaka_destination-wedding-2018-bdremux-1080p-ot-selezen-itunes" style="font-size: 12px !important; line-height: 14.6667px !important;">Как женить холостяка / Destination Wedding (2018) BDRemux 1080p от селезень | iTunes </a>
"""

from bs4 import BeautifulSoup
root = BeautifulSoup(text, 'html.parser')

for tr in root.select("tr.gai") + root.select("tr.tum"):
    tds = tr.select('td')

    # У второго td нужные нам <a>
    td = tds[1]

    # Выводим текст ячейки
    print(td.text.strip())

    # ВТОРОЙ СПОСОБ

    # У второго td берем третий <a>
    a = tds[1].select('a')[2]

    # Выводим текст ссылки
    print(a.text.strip())
    print()

Консоль:

Как женить холостяка / Destination Wedding (2018) BDRip от MegaPeer | iTunes
Как женить холостяка / Destination Wedding (2018) BDRip от MegaPeer | iTunes

Как женить холостяка / Destination Wedding (2018) BDRemux 1080p от селезень | iTunes
Как женить холостяка / Destination Wedding (2018) BDRemux 1080p от селезень | iTunes
8
  • ничего не дало :( вернуло пустоту 30 ноя 2018 в 13:01
  • и я ума не приложу как мне скопировать из инспектора мозиллы нужный мне код, он не выделяется кусками 30 ноя 2018 в 13:03
  • @AlexanderGninenko, так точно сработает: через правую кнопку мышки откройте исходный код страницы и оттуда выделите. Может такое быть, что таблица с торрентами подгружается после загрузки страницы? Например через ajax?
    – gil9red
    30 ноя 2018 в 13:06
  • добавил к главному посту, получился кабздец какой-то. Насчет того что вы спросили - честно, не знаю. 30 ноя 2018 в 13:10
  • @AlexanderGninenko слушайте, а у вас вообще что-то с rutor в скрипт отдается? Может у вас сайт заблокирован провайдером? Скрипт-то напрямую ходит, а не через прокси, как браузер
    – strawdog
    30 ноя 2018 в 13:12

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.