如何在 python 和 lxml 中使用 for 循环从网站链接列表中检索页面内容?

How to retrieve page content from a list of website links using a for loop in python and lxml?

我正在从一个网站上抓取数据,我已经检索到一个 URL 列表,我将从中获取我需要的最终数据。如何使用循环从此地址列表中检索 html?

在 lxml 中使用 xpath 我有一个 URL 列表。现在我需要为每个 URL 检索页面内容,然后再次使用 xpath 从每个页面获取最终数据。如果使用

,我可以从每个页面单独获取数据
pagecontent=requests.get(linklist[1])

然后我可以得到 1 url 的内容,但是如果我使用 for 循环

for i in range(0,8):
    pagecontent[i]=requests.get(linklist[i])

我收到错误列表分配索引超出范围。我也试过使用

pagecontent=[requests.get(linklist) for s in linklist]

我看到的错误是找不到连接适配器'['http...(list of links)...]'

我正在尝试获取列表页面内容,其中列表中的每个项目都有 html 个相应的 URL。实现此目标的最佳方法是什么?

根据您的评论,我相信这个(或类似的东西)可能就是您要找的;我不能自己尝试,因为我没有你的 linklist,但你应该能够修改代码以适应你的情况。它使用 python f-strings 来完成您需要的。

linklist = ['www.example_1.com','www.example_2.com','www.example_3.com']
pages = {} #initialize an empty dictionary to house your name/link entries

for i in range(len(linklist)):      
      pages[f'pagecontent[{i+1}]'] = linklist[i] #the '+1' is needed because python counts from 0...
for name, link in pages.items() :
    print (name, link)

输出:

pagecontent[1] www.example_1.com
pagecontent[2] www.example_2.com
pagecontent[3] www.example_3.com