【问题标题】:Not able to read column for HTML scraping无法读取 HTML 抓取的列
【发布时间】:2014-04-08 03:26:36
【问题描述】:

我正在尝试从http://en.wikipedia.org/wiki/Hybrid_electric_vehicles_in_the_United_States 抓取数据表

我使用了以下代码:

#!/usr/bin/env python
from mechanize import Browser
from BeautifulSoup import BeautifulSoup

mech = Browser()
url = "http://en.wikipedia.org/wiki/Hybrid_electric_vehicles_in_the_United_States"
page = mech.open(url)
html = page.read()
soup = BeautifulSoup(html)
table = soup.find("table",{ "class" : "wikitable" })

for row in table.findAll('tr')[1:]:
col = row.findAll('th')
Vehicle = col[0].string
Year1 = col[2].string
Year2 = col[3].string
Year3 = col[4].string
Year4 = col[5].string
Year5 = col[6].string
Year6 = col[7].string
Year7 = col[8].string
Year8 = col[9].string
Year9 = col[10].string
Year10 = col[11].string
Year11 = col[12].string
Year12 = col[13].string
Year13 = col[14].string
Year14 = col[15].string
Year15 = col[16].string
Year16 = col[17].string
record =(Vehicle,Year1,Year2,Year3,Year4,Year5,Year6,Year7,Year8,Year9,Year10,Year11,Year12,Year13,Year14,Year15,Year16)
print "|".join(record)

我收到这个错误

 File "scrap1.ph", line 13
    col = row.findAll('th')
      ^
IndentationError: expected an indented block

谁能告诉我我做错了什么。

【问题讨论】:

    标签: python beautifulsoup mechanize


    【解决方案1】:

    除了@traceur 关于缩进错误的观点,以下是您可以显着简化代码的方法:

    from mechanize import Browser
    from bs4 import BeautifulSoup
    
    mech = Browser()
    url = "http://en.wikipedia.org/wiki/Hybrid_electric_vehicles_in_the_United_States"
    soup = BeautifulSoup(mech.open(url))
    table = soup.find("table", class_="wikitable")
    
    for row in table('tr')[1:]:
        print "|".join(col.text.strip() for col in row.find_all('th'))
    

    请注意,不要使用from BeautifulSoup import BeautifulSoup(BeautifulSoup 的第 3 版),最好使用from bs4 import BeautifulSoup(第 4 版),因为第 3 版已不再维护。

    另外请注意,您可以将mech.open(url) 直接传递给BeautifulSoup 构造函数,而不是手动读取它。

    希望对您有所帮助。

    【讨论】:

    • 我的脚本仍然出现 IndentationError。请帮助我如何删除它。
    • @Auguster hm,这里没有缩进问题,请检查您是否已正确粘贴代码。
    • 我粘贴了相同的代码并得到了这个错误。文件“scrap1.py”,第 10 行打印“|”.join(col.text.strip() for col in row.find_all('th')) ^ IndentationError: expected an indented block
    • @Auguster 缩进以print开头的行。
    • 我所要做的就是将打印行与 for 循环放在同一行,这可能是因为我正在 Windows 中编辑并使用 cygwin 运行代码。
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2018-11-17
    • 2019-11-22
    • 2020-04-22
    • 2012-09-29
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多