【问题标题】:Creating dictionary with scraped values (Beautiful Soup Python)用刮掉的值创建字典(Beautiful Soup Python)
【发布时间】:2017-07-13 17:00:20
【问题描述】:

我正在尝试从两个抓取的数据数组中创建一个字典。此代码中的所有内容都有效,除了最后一步,它会引发以下错误:

----------------------------------- ---------------------------- TypeError Traceback (last last call last) in () 19 tale_data_governors = [table_data_governors 中数据的数据字符串] 20 ---> 21 字典 = dict(zip(table_data_governors,table_data))

TypeError: 'list' 对象不可调用

#Return the results in dictionary form 
#{'Brown': 56.0126582278481, 'Whitman': 43.9873417721519}

html = requests.get("https://www.realclearpolitics.com/epolls/2010/governor/ca/california_governor_whitman_vs_brown-1113.html").text

soup = BeautifulSoup(html, 'html.parser')

#Scrape the percentage Numbers
table = soup.find_all('table')[0]
table_row = table.find_all('tr')[1]
table_data = table_row.find_all('td')[3:5]

#Scrape the Names
table_row_governors = table.find_all('tr')[0]
table_data_governors = table_row_governors.find_all('th')[3:5]
table_data_governors

table_data = [data.string for data in table_data]
tale_data_governors = [data.string for data in table_data_governors]

dictionary = dict(zip(table_data_governors,table_data))

任何帮助/建议将不胜感激!

谢谢

编辑:我认为这可能与此有关:

[(<th>Brown (D)</th>, u'53.1'), (<th>Whitman (R)</th>, u'41.7')]

这是我调用 zip() 时得到的元组数组。我不太清楚为什么会这样。我认为 data.string 会将这些转换为字符串..

编辑 2:此代码有效

a = zip(table_data, table_data_governors)

b = {}
for x,y in a:
    b[y] = x

b

奇怪的东西。可能与 Ipython 笔记本有关。

【问题讨论】:

  • 你能提供完整的错误信息吗?
  • 是的,刚刚编辑过
  • 我在 python 2 和 3 中运行了您的代码,但没有收到此错误...您发布的代码与您正在运行的代码相同吗?还有你用的是哪个版本的请求和漂亮的汤?
  • 是的,代码完全一样。如何在 ipython notebook 中找到版本
  • 您的代码中可能存在拼写错误。 tale_data_governors 正在被定义,table_data_governors 稍后会被调用。这应该可以解决问题。

标签: python screen-scraping


【解决方案1】:

您的代码中有错字。

您已定义tale_data_governors,稍后将调用table_data_governors

【讨论】:

    猜你喜欢
    • 2016-10-28
    • 2022-07-20
    • 1970-01-01
    • 2018-04-22
    • 2014-02-08
    • 2021-03-11
    • 2018-11-07
    • 2016-02-27
    • 2021-10-18
    相关资源
    最近更新 更多