【问题标题】:Trying to understand Python Beautiful Soup parsing code试图理解 Python Beautiful Soup 解析代码
【发布时间】:2015-10-09 02:16:52
【问题描述】:

我遇到了以下代码,我发现它非常有用,但不知道如何解释其中的一部分。

from pprint import pprint
import urllib2
from bs4 import BeautifulSoup

url = 'http://en.wikipedia.org/wiki/List_of_Bollywood_films_of_2014'
soup = BeautifulSoup(urllib2.urlopen(url))

headers = ['Opening', 'Title', 'Genre', 'Director', 'Cast']
results = {}

for block in soup.select('div#mw-content-text > h3'):
    title = block.find('span', class_='mw-headline').text
    rows = block.find_next_sibling('table', class_='wikitable').find_all('tr')

    results[title] = [{header: td.text for header, td in zip(headers, row.find_all('td'))}
                      for row in rows[1:]]

pprint(results)

除了这一段我都明白了:

    results[title] = [{header: td.text for header, td in zip(headers, row.find_all('td'))}
                      for row in rows[1:]]

谁能解释这是在做什么以及我应该如何阅读它?谢谢!

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    那一行基本上可以分解成这个。

    for count, row in enumerate(rows[1:]):
        for header, td in zip(headers, row.find_all('td'):
            results[title][count][header] = td.text
    

    【讨论】:

      猜你喜欢
      • 2013-10-21
      • 2012-06-12
      • 2011-09-27
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-21
      • 2018-11-26
      相关资源
      最近更新 更多