【问题标题】:Python scraping delete duplicatesPython抓取删除重复项
【发布时间】:2019-03-14 13:46:20
【问题描述】:

我不想有两次电子邮件地址,使用此代码我收到错误 类型错误:不可散列类型:“列表” 所以我假设这条线 allLinks=set() 错了,我必须使用元组而不是列表,对吗?

这是我的代码:

import requests
from bs4 import BeautifulSoup as soup
def get_emails(_links:list):

for i in range(len(_links)):
 new_d = soup(requests.get(_links[i]).text, 'html.parser').find_all('a', {'class':'my_modal_open'})
 if new_d:
   yield new_d[-1]['title']


start = 20
while True:
d = soup(requests.get('http://www.schulliste.eu/type/gymnasien/?bundesland=&start={page_id}'.format(page_id=start)).text, 'html.parser')
results = [i['href'] for i in d.find_all('a')][52:-9]
results = [link for link in results if link.startswith('http://')]



next_page=d.find('div', {'class': 'paging'}, 'weiter')

if next_page:

    start+=20

else:
    break

allLinks= set() 

if results not in allLinks:


    print(list(get_emails(results)))

    allLinks.add(results)

【问题讨论】:

  • 没错。列表不能用作字典中的键或集合中的值。您必须将列表转换为元组。但请记住(1, 2, 3) != (2, 1, 3),所以要小心。
  • 你可能想update 集合而不是add 项目给它
  • 我该怎么做?
  • @radonrace 搜索“更新”在:docs.python.org/2/library/sets.html#set-objects
  • 好的,但这并不能解决列表元组的问题,对吧?

标签: python beautifulsoup duplicates screen-scraping


【解决方案1】:

我让它工作了,但我仍然收到重复的电子邮件。

    allLinks = []

if results not in allLinks:


    print(list(get_emails(results)))

    allLinks.append((results))

有人知道为什么吗?

【讨论】:

    【解决方案2】:

    您正在尝试将整个电子邮件列表添加为 set 中的单个条目。

    您想要的是在单独的set 条目中添加实际电子邮件。

    问题出在这一行:

    allLinks.add(results)
    

    它将整个 results 列表作为单个元素添加到 set 中,但这是行不通的。改用这个:

    allLinks.update(results)
    

    这将使用list 中的元素更新set,但每个元素将是set 中的一个单独条目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-26
      • 2019-05-12
      • 2015-12-29
      • 2012-10-09
      相关资源
      最近更新 更多