Skip to main content
 首页 » 编程设计

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

2025年02月15日8zlslch

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

--------------------------------------------------------------------------- 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。