首页 > 解决方案 > 尝试将项目添加到python中的列表

问题描述

我正在尝试使用 Beautifulsoup 从网站收集链接。

from bs4 import BeautifulSoup
import requests

address="http://transcripts.cnn.com/TRANSCRIPTS/2018.04.29.html"
page = requests.get(address)
soup = BeautifulSoup(page.content, 'html.parser')

articles =[]
for links in soup.find_all('div', {'class':'cnnSectBulletItems'}):
    for link in soup.find_all('a'):
        article = link.get('href')
        articles.append(article)
        print(article)

在此处输入图像描述

有两个问题:

  1. 存在重复的链接
  2. print 命令表明代码找到了链接,但是列表中的文章不包含任何元素。

有谁知道发生了什么?

标签: python

解决方案


您可以使用Set(没有重复元素的无序集合)来删除重复链接。

for links in soup.find_all('div', {'class':'cnnSectBulletItems'}):
    links = set(links.find_all('a'))
    for link in links:
        print(link.get('href')) 

推荐阅读