【发布时间】:2019-10-18 15:57:24
【问题描述】:
我正在网络抓取并尝试将第一个链接附加到链接列表中(使用列表理解),但我遇到了麻烦。我浏览了很多让我很接近的帖子,但不完全是。我要么收到错误(如下所示),要么收到所有链接(不仅仅是每个 URL 的第一个)。我已经尝试过显示here 的解决方案,但在 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.x web-scraping beautifulsoup list-comprehension