python - 使用 lxml 和请求解析 HTML 列表的问题

标签 python html html-parsing lxml python-requests

我有一个 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/

相关文章:

html - CSS - Div 不会计算子 div

python - BeautifulSoup - 从 JS 中提取特定的 JSON 键值

python - 抓取嵌套标签

python - 使用多线程 Raspberry pi B+ 运行多个脚本

python - 我在 Python v 3.3.2 中遇到集合和元组问题

html - 排队脚本未显示在头部

javascript - javascript regex .match 只找到一个结果

python - '导入错误 : No module named dumbnet' when trying to run a script that leverages scapy on OS X

python - 解析 HTML 未输出所需数据(FedEx 的跟踪信息)

javascript - 根据图片制作工作流程图