首页 > 解决方案 > 将子列表中的行附加到新列表

问题描述

我正在网络抓取并尝试将第一个链接附加到链接列表中(使用列表理解),但我遇到了麻烦。我浏览了很多让我很接近的帖子,但不完全是。我要么收到错误(如下所示),要么收到所有链接(不仅仅是每个 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']

标签: python-3.xweb-scrapingbeautifulsouplist-comprehension

解决方案


不需要列表理解:

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())除非你真的需要一个空列表在你的结果中做得更好。


推荐阅读