python - 尝试将项目添加到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)
有两个问题:
- 存在重复的链接
- print 命令表明代码找到了链接,但是列表中的文章不包含任何元素。
有谁知道发生了什么?
解决方案
您可以使用Set(没有重复元素的无序集合)来删除重复链接。
for links in soup.find_all('div', {'class':'cnnSectBulletItems'}):
links = set(links.find_all('a'))
for link in links:
print(link.get('href'))
推荐阅读
- css - 页脚和内容之间的空间
- c# - 如何从 wpf 应用程序的 MVVM 设计模式中的视图模型触发视图上的功能
- javascript - 如何使用 Promise 让此代码正常工作?
- css - 我可以通过 userchrome 禁用“谷歌翻译栏”吗?
- python-3.x - 将特定列值更改为 sklearn 建模的因子或水平
- javascript - 我正在尝试将列表推送到控制台,但它无法正常工作并不断将代码推送到列表中
- python - python库创建python服务器和客户端,也可以处理本地python类型的端口上的数据传输
- excel - 有没有办法根据 VBA 读取单元类型格式化单元格?
- javascript - 澄清 Typescript 的目标和库设置的功能
- javascript - 在 xmpp 群聊中发送聊天标记