【问题标题】:Python Requests Go to Link and DownloadPython 请求转到链接和下载
【发布时间】:2016-04-19 14:27:42
【问题描述】:

我想以自动化方式执行以下操作:

  1. 转到此链接:https://www.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/MCRAdvPartDEnrolData/Monthly-Enrollment-by-Contract-Plan-State-County-DL.xml

  2. 点击页面最底部的链接(以当前年份和月份结尾(即http://www.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/MCRAdvPartDEnrolData/Monthly-Enrollment-by-Contract-Plan-State-County-Items/Monthly-Enrollment-by-CPSC-2016-04.html

  3. 在下一页,从“下载”下的顶部链接下载 zip 文件: CPSC 每月注册 - 2016 年 4 月 [ZIP, 20MB]

到目前为止,我有以下获取当前年份和月份的信息,但我需要其他帮助...

from datetime import datetime
import calendar
Day = datetime.now().day
Month = datetime.now().month
Year = datetime.now().year
m=calendar.month_name[Month]

【问题讨论】:

    标签: python python-3.x web-scraping python-requests


    【解决方案1】:

    您需要一个 XML 解析器来从 XML 提要中提取链接,并需要一个 HTML 解析器来提取到 zip 文件的链接。为此,我们将分别使用lxml.etreelxml.html。工作实施:

    from datetime import datetime
    from urllib.request import urlretrieve
    from urllib.parse import urljoin
    
    import requests
    from lxml import etree
    from lxml import html
    
    
    date_part = datetime.now().strftime("%Y-%m")
    with requests.Session() as session:
        # get the XML feed and extract the link
        response = session.get("https://www.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/MCRAdvPartDEnrolData/Monthly-Enrollment-by-Contract-Plan-State-County-DL.xml")
        root = etree.fromstring(response.content)
        link = root.xpath("//item/link[contains(., '-%s.html')]/text()" % date_part)[0]
    
        # follow the link and extract the link to the zip file
        response = session.get(link)
        root = html.fromstring(response.content)
        zip_link = root.xpath("//a[@type='application/zip']/@href")[0]
        link = urljoin(link, zip_link)
    
        # download zip
        urlretrieve(link, filename="my.zip")
    

    【讨论】:

    • 你好。我在 Python 3.5 中使用 Anaconda,但出现此错误: ImportError: cannot import name 'urlretrieve' 我试过 pip install urllib 但它已经安装了。你遇到过这种情况吗?
    • @DanceParty2 抱歉,已修复导入,请重新检查。
    • 如果您从未使用过 Python 和 Web,我建议您尝试 Selenium!有了它,您也可以真正了解正在发生的事情并解决非常复杂的任务。它还与 lxml 共享一些语法,您将了解 HTML 以及如何解析网页。为了帮助您入门,您可以访问Selenium Homepage 并获取他们的 Firefox-Addon。
    • @Krazor 这始终是一个选项,但问题是 python-requests 具体由标题和标签判断。还是谢谢。
    • @DanceParty2 您可以提供filename 参数并设置自定义路径..我已经更新了答案中的代码-将zip文件保存到当前目录中的my.zip文件中。希望对您有所帮助。
    猜你喜欢
    • 2021-12-08
    • 2018-11-24
    • 2022-12-05
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多