【问题标题】:Extract Data From wikipedia using Beautiful soup使用 Beautiful soup 从维基百科中提取数据
【发布时间】:2014-08-05 11:16:50
【问题描述】:

我有一个维基百科页面:http://en.wikipedia.org/wiki/2014_AFL_season

我需要准备一个字典,以 Round 为键,对应的数据为值。

喜欢:

myDict = {"Round 1": [["Date","Loser Team ", "Winner Team ","Stadium", "Crowd"],  ["Date","Loser Team ", "Winner Team ","Stadium", "Crowd"].......], "Round 2":[["Date","Loser Team ", "Winner Team ","Stadium", "Crowd"],  ["Date","Loser Team ", "Winner Team ","Stadium", "Crowd"].......]

所以这本词典将存储所有数据。

请帮我做这件事。我在 Python 中使用 BS4 和 urllib2。

我使用了以下代码:

from bs4 import BeautifulSoup
import urllib2



header = {'User-Agent': 'Mozilla/5.0'}

def createLink():

    url = "http://en.wikipedia.org/wiki/2014_AFL_season"

#     mainPage = urllib2.Request(url,headers=header)

    mainPage = urllib2.urlopen(url)

    mainPageSoup = BeautifulSoup(mainPage)

    for index in mainPageSoup.findAll("table"):
        print index

createLink()

【问题讨论】:

  • 向我们展示您的 BS 代码。
  • 在真正编写代码之前,我试图弄清楚。我很困惑并发布了问题
  • 我的猜测,也许完全错误,你会在 wiki 代码中找到更多结构(即进入“编辑”),这样更容易解析。
  • 这个问题似乎是题外话,因为它要求代码并且没有显示任何努力。
  • 这里给代码,给我点时间

标签: python beautifulsoup


【解决方案1】:

利用每个表格前面都有一个带有圆形的H3元素这一事实:

rounds = {}

for table in soup.select('h3 + table'):
    round_name = table.find_previous_sibling('h3').span.get_text().strip()
    if not round_name.lower().startswith('round'):
        break  # all rounds found
    entries = []
    for row in table.find_all('tr', style=False):
        cells = row.find_all('td')
        if len(cells) < 5:
            continue
        date = cells[0].get_text()
        loser = cells[1].a.get_text()
        winner = cells[3].a.get_text()
        venue = cells[4].a.get_text()
        crowd = cells[4].a.next_sibling.strip(' \n()')
        rounds[round_name] = [date, loser, winner, venue, crowd]

【讨论】:

  • 我使用了你的建议但得到了这个错误:round_name = table.previous_sibling('h3').get_text().strip() TypeError: 'NavigableString' object is not callable
猜你喜欢
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多