从标签beautifulsoup python中提取类名

问题描述 投票:5回答:2

我有以下HTML代码:

    <td class="image">
      <a href="/target/tt0111161/" title="Target Text 1">
       <img alt="target img" height="74" src="img src url" title="image title" width="54"/>
      </a>
     </td>
     <td class="title">
      <span class="wlb_wrapper" data-caller-name="search" data-size="small" data-tconst="tt0111161">
      </span>
      <a href="/target/tt0111161/">
       Other Text
      </a>
      <span class="year_type">
       (2013)
      </span>

我正在尝试使用漂亮的汤将某些元素解析为制表符分隔的文件。我得到了很多帮助,并且:

for td in soup.select('td.title'):
 span = td.select('span.wlb_wrapper')
 if span:
     print span[0].get('data-tconst') # To get `tt0082971`

现在我想得到“目标文本1”。

我尝试了一些类似上面文字的内容,例如:

for td in soup.select('td.image'): #trying to select the <td class="image"> tag
img = td.select('a.title') #from inside td I now try to look inside the a tag that also has the word title
if img:
    print img[2].get('title') #if it finds anything, then I want to return the text in class 'title'
python html parsing beautifulsoup
2个回答
3
投票

如果你试图根据类得到一个不同的td(即td class =“image”和td class =“title”,你可以使用美丽的汤作为字典来获得不同的类。

这将在表中找到所有td class =“image”。

from bs4 import BeautifulSoup

page = """
<table>
    <tr>
        <td class="image">
           <a href="/target/tt0111161/" title="Target Text 1">
            <img alt="target img" height="74" src="img src url" title="image title" width="54"/>
           </a>
          </td>
          <td class="title">
           <span class="wlb_wrapper" data-caller-name="search" data-size="small" data-tconst="tt0111161">
           </span>
           <a href="/target/tt0111161/">
            Other Text
           </a>
           <span class="year_type">
            (2013)
           </span>
        </td>
    </tr>
</table>
"""
soup = BeautifulSoup(page)
tbl = soup.find('table')
rows = tbl.findAll('tr')
for row in rows:
    cols = row.find_all('td')
    for col in cols:
        if col.has_attr('class') and col['class'][0] == 'image':
            hrefs = col.find_all('a')
            for href in hrefs:
                print href.get('title')

        elif col.has_attr('class') and col['class'][0] == 'title':
            spans = col.find_all('span')
            for span in spans:
                if span.has_attr('class') and span['class'][0] == 'wlb_wrapper':
                    print span.get('data-tconst')

0
投票

span.wlb_wrapper是用于选择<span class="wlb_wrapper" data-caller-name="search" data-size="small" data-tconst="tt0111161">的选择器。有关选择器的更多信息,请参阅thisthis

将你的python代码span = td.select('span.wlb_wrapper')改为span = td.select('span')span = td.select('span.year_type'),看看它返回的内容。

如果你尝试上面并分析span持有什么,你将得到你想要的。

© www.soinside.com 2019 - 2024. All rights reserved.