python-3.x - 将子列表中的行附加到新列表
问题描述
我正在网络抓取并尝试将第一个链接附加到链接列表中(使用列表理解),但我遇到了麻烦。我浏览了很多让我很接近的帖子,但不完全是。我要么收到错误(如下所示),要么收到所有链接(不仅仅是每个 URL 的第一个)。我已经尝试过此处显示的解决方案,但在 Navigable String 周围出现了不同的错误。请参阅下面的我以前的代码、错误和我的理想输出。感谢您的任何帮助!
代码
dfkf['URL'][0:5].values =
['https://www.sec.gov/Archives/edgar/data/867028/0001493152-19-010877-index.htm',
'https://www.sec.gov/Archives/edgar/data/1438901/0001161697-19-000350-index.htm',
'https://www.sec.gov/Archives/edgar/data/1750/0001047469-19-004266-index.htm',
'https://www.sec.gov/Archives/edgar/data/1138723/0001564590-19-032909-index.htm',
'https://www.sec.gov/Archives/edgar/data/1650101/0001493152-19-009992-index.htm']
x = []
for URL in dfkf['URL'][0:5].values:
r = requests.get(str(URL))
soup = BeautifulSoup(r.text, 'html.parser')
x.append([line['href'] for line in list(soup.find_all(text = re.compile('xml'), href=True))][0])
错误 IndexError:列表索引超出范围
理想输出(返回链接列表中的第一个链接)
x= ['/Archives/edgar/data/867028/000149315219010877/etfm-20181231.xml',
[],
'/Archives/edgar/data/1750/000104746919004266/air-20190531.xml',
'/Archives/edgar/data/1138723/000156459019032909/aray-20190630.xml',
'/Archives/edgar/data/1650101/000149315219009992/atxg-20190331.xml']
解决方案
不需要列表理解:
for URL in dfkf['URL'][0:5].values:
r = requests.get(str(URL))
soup = BeautifulSoup(r.text, 'html.parser')
links = soup.find_all(text=re.compile('xml'), href=True)
if links:
x.append(links[0]['href'])
else:
x.append(list())
编辑:可能x.append(None)
比x.append(list())
除非你真的需要一个空列表在你的结果中做得更好。
推荐阅读
- javascript - 通过字符串从数组中删除多个对象
- php - 当 PDO::ATTR_EMULATE_PREPARE = false 时 PHP PDO 失败
- r - 在 DigitalOcean ubuntu 服务器上托管闪亮的应用程序时出错
- python - 为什么我不能重塑或调整我的 numpy 数组的大小
- python-3.x - Tkinter 画布慢
- html - 为什么绝对定位的 div 被绘制在其相对定位的 div 兄弟之下?
- kubernetes - 如何在 Kubernetes 集群上引导 juju?
- javascript - BootstrapVue 在 b 表中插入图像
- sql - 相关和不相关的 SQL 查询放在一起
- azure-keyvault - 如何将 Azure Key Vault 滚动证书与 OpenIddict 一起使用?