【问题标题】:How do I use the python urllib library to open web pages with a variable included in the url address?如何使用 python urllib 库打开 url 地址中包含变量的网页?
【发布时间】:2019-01-13 23:32:45
【问题描述】:

这是我的代码:

输入您要查找的年份和文件类型

year = input('What year is the master index you are looking for?\n')
file = input('What form are you looking for?\n')
import urllib.request
index_url = urllib.request.urlopen('https://www.sec.gov/Archives/edgar/full-index/%s/QTR2/master.idx'%(year))

这会打开与我指定为变量的年份对应的网页吗?

感谢您的帮助!

【问题讨论】:

    标签: python web web-crawler


    【解决方案1】:

    如果你想下载文件并在你的脚本中操作它,你可能想做这样的事情......

    import requests
    year = input('What year is the master index you are looking for?\n')
    url = 'https://www.sec.gov/Archives/edgar/full-index/%s/QTR2/master.idx' % year
    resp = requests.get(url)
    print(resp.text)
    

    这将获取构造的 URL 并打印返回的内容。我在这里使用了 requests 而不是 urllib,这是现在大多数人喜欢使用的,因为它非常简单易用,它也支持 Python 2 和 3,你可以通过 PyPi 安装它,例如pip install requests.

    【讨论】:

    • 非常感谢您的帮助!我还有一个问题。有没有办法使用字符串格式在 url 变量中添加变量 year 和 form ?即用户输入所需的年份和表格,并且两者都被插入到预定义位置的 url 中?
    • 是的,你可以这样做,这样的事情应该可以工作...... my_url = 'http://blabla.com/bla/%s/hello/page/%s/' % (year, form) 括号内的变量按照它们出现在每个相应 %s 的顺序插入到 URL 中。跨度>
    猜你喜欢
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-29
    • 1970-01-01
    相关资源
    最近更新 更多