如何使用Python读取URL的内容?

发布于 2021-01-29 19:35:59

当我将其粘贴到浏览器中时,以下方法起作用:

http://www.somesite.com/details.pl?urn=2344

但是,当我尝试使用Python读取URL时,没有任何反应:

 link = 'http://www.somesite.com/details.pl?urn=2344'
 f = urllib.urlopen(link)           
 myfile = f.readline()  
 print myfile

我需要对URL进行编码,还是没有看到什么?

关注者
0
被浏览
108
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    要回答您的问题:

    import urllib
    
    link = "http://www.somesite.com/details.pl?urn=2344"
    f = urllib.urlopen(link)
    myfile = f.read()
    print(myfile)
    

    您需要read(),而不是readline()

    编辑(2018-06-25):自Python
    3起,旧版urllib.urlopen()被替换为urllib.request.urlopen()(有关详细信息,请参阅https://docs.python.org/3/library/urllib.request.html#urllib.request.urlopen中的注释)


    或者,只需在此处获取此库:http :
    //docs.python-requests.org/en/latest/并认真使用它即可:)

    import requests
    
    link = "http://www.somesite.com/details.pl?urn=2344"
    f = requests.get(link)
    print(f.text)
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看