【问题标题】:How to find a sibling HTML table element by specific href using Python Beautiful Soup如何使用 Python Beautiful Soup 通过特定的 href 查找同级 HTML 表格元素
【发布时间】:2020-06-30 14:14:38
【问题描述】:

使用 Beautiful Soup,我正在尝试从 HTML 表中抓取数据,如下所示:

<table class="ipl-zebra-list ipl-zebra-list--fixed-first release-dates-table-test-only">
  <tr class="ipl-zebra-list__item release-date-item">
   <td class="release-date-item__country-name"><a href="/calendar/?region=de">Germany
   </a></td>
   <td align="right" class="release-date-item__date">15 September 2017</td> <td align="left" class="release-date-item__attributes">(Oldenburg Film Festival)
   </td>
  </tr>
  <tr class="ipl-zebra-list__item release-date-item">
    <td class="release-date-item__country-name"><a href="/calendar/?region=gb">UK
    </a></td>
    <td align="right" class="release-date-item__date">23 March 2018</td> <td class="release-date-item__attributes--empty"></td>
 </tr>
</table>

我正在寻找出现在 &lt;td&gt; 元素的兄弟元素中的日期,其中包括以下 href:

<a href="/calendar/?region=gb">UK

在上面的示例中,此日期为 2018 年 3 月 23 日,但出现 href 的每个实例的日期都不同。但是 href 总是相同的。

总而言之,我正在寻找出现在与上面列出的 href 相邻单元格中的数据。

谢谢!

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    因此,如果您想将国家名称和日期链接到该国家/地区名称,您可以创建一个这样的字典:

    html = '''<table class="ipl-zebra-list ipl-zebra-list--fixed-first release-dates-table-test-only">
      <tr class="ipl-zebra-list__item release-date-item">
       <td class="release-date-item__country-name"><a href="/calendar/?region=de">Germany
       </a></td>
       <td align="right" class="release-date-item__date">15 September 2017</td> <td align="left" class="release-date-item__attributes">(Oldenburg Film Festival)
       </td>
      </tr>
      <tr class="ipl-zebra-list__item release-date-item">
        <td class="release-date-item__country-name"><a href="/calendar/?region=gb">UK
        </a></td>
        <td align="right" class="release-date-item__date">23 March 2018</td> <td class="release-date-item__attributes--empty"></td>
     </tr>
    </table>'''
    
    
    html_code = BeautifulSoup(html, 'html.parser')
    
    countries = html_code.find_all('td', class_='release-date-item__country-name')
    dates = html_code.find_all('td', class_='release-date-item__date')
    
    dates_as_dic = {}
    for i in range(len(dates)):
        dates_as_dic[countries[i].text.strip()] = dates[i].text
    
    print(dates_as_dic)
    

    输出:

    {'Germany': '15 September 2017', 'UK': '23 March 2018'}
    

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 1970-01-01
      • 2018-10-24
      • 2017-05-31
      • 2020-11-25
      • 2019-11-23
      • 1970-01-01
      • 2019-06-02
      • 2021-01-02
      相关资源
      最近更新 更多