我有一个 URL 列表存储在变量 href
中。当我通过下面的函数传递它时,唯一返回的 recipe_links 来自 href
中的第一个 URL。我的代码有明显的错误吗?我不确定为什么它不会遍历我存储在 href
中的所有 20 个 URL。我为 href
中的第一个 URL 获得的返回结果按预期检索,但我无法循环到下一个 URL。
def first_page_links(link):
recipe_links = []
recipe_html = []
for x in link:
page_request = requests.get(x)
recipe_html.append(html.fromstring(page_request.text))
print recipe_html
for x in recipe_html:
recipe_links.append(x.xpath('//*[@id="content"]/ul/li/a/@href'))
return recipe_links
最佳答案
注意 return
的放置位置。您可能希望在所有循环完成后返回:
def first_page_links(link):
recipe_links = []
recipe_html = []
for x in link:
page_request = requests.get(x)
recipe_html.append(html.fromstring(page_request.text))
print recipe_html
for x in recipe_html:
recipe_links.append(x.xpath('//*[@id="content"]/ul/li/a/@href'))
return recipe_links
关于python - 使用 lxml 和请求解析 HTML 列表的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22870508/