python - 用抓取的值创建字典(Beautiful Soup Python)

标签 python screen-scraping

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

--------------------------------------------------------------------------- TypeError Traceback (most recent call last) in () 19 tale_data_governors = [data.string for data in table_data_governors] 20 ---> 21 dictionary = dict(zip(table_data_governors,table_data))

TypeError: 'list' object is not callable

#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 笔记本有关。

最佳答案

您的代码中有错别字。

您已定义 tale_data_governors 并稍后调用 table_data_governors

关于python - 用抓取的值创建字典(Beautiful Soup Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45086945/

相关文章:

asp.net - 使用 Ruby 抓取 ASP.NET 站点

html - scrapy 将 InitSpider 转换为 CrawlSpider w/login

python - 如何从静态网站开始查询?

python - Python 中迭代两个键

python - Django 1.8 : Help making filenames RELATIVE

python - 如何随机排序图像及其掩码?

python - 将实时公共(public)线路输出重定向到 Django HttpResponse

python - 如何使用正则表达式选择字符串的特定部分?

python - Mechanicalize 响应不返回任何内容

python - 具有 "load more"分页的列表的 BeautifulSoup 子页面